DRYな備忘録

Don't Repeat Yourself.

個人的におせっかいだなと感じたGo言語の仕様

Go言語は、必要なものを提供し、必要じゃないものは削ぎ落とし、明示的でとても学びやすい言語だと思ってます。好きです。「なるほど、ここからは自分でやれ、ということか、面白い」「おーこんなこともしてくれちゃうのかー」という発見こそあれ、「なんでこここうなってんねん」という体験は今まで無かったです。

が、

今日はじめてGo言語がちょっとだけ嫌いになりました。言語仕様というか、標準パッケージfmtの仕様。以下のコード、

func main() {
    a := &A{Name: "otiai10"}
    fmt.Printf("%+v\n", a)
}

みんな大好きfmtパッケージ。

&{Name:otiai10}

こうだと思ってた

結果

ほげら

ふぇぇ

なぜなら

package main

import "fmt"

type A struct {
    Name string
}

func (a *A) String() string {
    return "ほげら"
}

func main() {
    a := &A{Name: "otiai10"}
    fmt.Printf("%+v\n", a)
}

Go Playground

よく見たら

4 If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

ちゃんと書いてあった

(要らねえよJavaかよ)

f:id:otiai10:20141204202515g:plain

ハイ、すみませんでした

DRYな備忘録