英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论