初始化自定义类型

huangapple go评论65阅读模式
英文:

Initializing custom type

问题

有人可以帮我理解以下情况吗?

有一个自定义类型

type Foo string

这个构造可以工作:

var foo Foo = "foo"
fmt.Printf("\n%s", foo)

而这个却不行:

var bar = "bar"
var foo Foo = bar
fmt.Printf("\n%s", foo)

会报错cannot use bar (variable of type string) as type Foo in variable declaration. 有什么区别,我该如何正确初始化这个类型?
谢谢 😊

英文:

Can someone help me to understand the following situation?

Having a custom type

type Foo string

This construction works:

var foo Foo = "foo"
fmt.Printf("\n%s", foo)

And this:

var bar = "bar"
var foo Foo = bar
fmt.Printf("\n%s", foo)

Throws a cannot use bar (variable of type string) as type Foo in variable declaration. What are the differences and how can I initialize this type properly?
Thanks 🙂

答案1

得分: 1

最后一个不起作用是因为Go语言有强类型检查;而且如果Foo的基本类型是string,它本身并不是一个string类型。

因此,你不能将一个字符串赋值给它。

要实现你想要的效果,你需要进行类型转换:

func main() {
	var a = "hello"
	var b Foo
	b = Foo(a)
	fmt.Println("b:", b)
}
英文:

The last one doesn't work because Go has strong type check; also if Foo has string as base type, it's not a string.

For that reason you cannot assign a string to it.

to achieve what you want you have to do casting

func main() {
	var a = "hello"
	var b Foo
	b = Foo(a)
	fmt.Println("b:", b)
}

答案2

得分: 1

让我来纠正一下:

var bar = "bar"
var foo Foo = Foo(bar)
fmt.Printf("\n%s", foo)

或者只需简化为:

var foo = Foo(bar)
英文:

Let me correct this

var bar = "bar"
var foo Foo = Foo(bar)
fmt.Printf("\n%s", foo)

or just

var foo = Foo(bar)

huangapple
  • 本文由 发表于 2022年5月27日 20:56:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/72405796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定