LoginSignup
2
0

More than 3 years have passed since last update.

Go言語でNamed Typesで定義した変数に基底型の値を入れようとするとエラーがでる

Posted at

遭遇した問題

Go言語にて Named Types で定義した変数に基底型の値を入れようとすると以下のエラーをはく。
cannot use hogehoge (variable of type string) as fugafuga value in variable declaration

内容

type NameType string // named types

func funcName (val string) {
    var nt NameType = val // ここでerror
}

解決策

type NameType string

func funcName (val string) {
    nt := NameType(val)// ok
}

原因

変数を経由して代入しようとすると、 型が確定している ため、「型が違うよ!」 というエラーが出る。
変数を経由せず、値をそのままいれるか、

type NameType string

var nt NameType = "row data"

変数を経由する場合は以下のようにする。

type NameType string

val = "row data"
nt := NameType(val)

まとめ


type MyString string
var x MyString
x = "hogehoge" //<-これはできる
s := "hugahuga"
//x = s  <- これはできない
x = MyString(s) // <-これはできる
2
0
0

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
2
0