LoginSignup
3
3

More than 5 years have passed since last update.

Golang Interfaceの使い方 その2

Last updated at Posted at 2016-01-23

Golang interfaceの使い方という記事を書いたが、ちょっと難しく考えすぎていたかもしれない。

JavaScriptでthisとPrototypeを使ってOOPするのとおなじように考えれば理解しやすいのかも。

問題

ここから引用

文字列と数字を渡すと数字の文だけ文字列を繰り返して出力しろ
例えば "abc" と 3 だと "abcabcabc"のようになる。

解法への考え方

単純に引数を食わせてやればいいのだが、GoでFunctionに文字列と数字のように違ったタイプの引数を食わせるやり方が良くわからなかった。

で、いろいろ考えた末にInterfaceを使ってみた。
(ちゃんとしたやり方はコメント欄を参照のこと。)

テストコード

package repeatString

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func Test(t *testing.T) {
    assert.Equal(t, Repeat{words: "*", num: 3}.repeat(), "***", "1")
    assert.Equal(t, Repeat{words: "abc", num: 3}.repeat(), "abcabcabc", "2")
    assert.Equal(t, Repeat{words: "abc", num: 4}.repeat(), "abcabcabcabc", "3")
    assert.Equal(t, Repeat{words: "abc", num: 1}.repeat(), "abc", "4")
    assert.Equal(t, Repeat{words: "*", num: 8}.repeat(), "********", "5")
    assert.Equal(t, Repeat{words: "abc", num: -2}.repeat(), "", "6")
}

コード

package repeatString

type Repeat struct {
    words string
    num   int
}

func (r Repeat) repeat() string {
    var s string

    for i := 1; i <= r.num; i++ {
        s += r.words
    }
    return s
}

回りくどいがJSでやるとこんな感じ

function repeat(str, num) {
    doRepeat = new Repeater(str, num)
    doRepeat.doRepeat()
}

function Repeater(str, num) {
    this.str = str
    this.num = num
}

Repeater.prototype.doRepeat = function() {
    var s = ""
    self = this
    for (var i = 1; i <= self.num; i++) {
        s += self.str
    };
    console.log(s)
    return s
}
3
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3