定義済みの型を名前で再定義するだけのカスタム型がある場合:
type Answer string
そして、事前定義された型を受け入れる関数でそれを使用しようとします:
func acceptMe(str string) {
fmt.Println(str)
}
func main() {
type Answer string
var ans Answer = "hello"
// cannot use ans (type Answer) as type string in function argument
acceptMe(ans)
// invalid type assertion: ans.(string) (non-interface type Answer on left)
acceptMe(ans.(string))
// Does work, but I don't understand why if the previous doesn't:
acceptMe(string(ans))
}
型アサーションは失敗するのに、変換は機能するのはなぜですか?