英文:
Convert string to Foo (type string)
问题
这个例子将会被简化,去掉我正在做的自定义 XML 解析部分,但是我遇到了这个问题:
package main
import (
"encoding/xml"
"fmt"
)
type Foo string
func main() {
var f Foo
var b string
c := xml.CharData{}
f = string(c)
b = string(c)
fmt.Println(b)
}
//prog.go:15: cannot use string(c) (type string) as type Foo in assignment
Foo 是一个字符串类型,我错过了什么,无法将 xml.CharData 的字符串表示(它是有效的,在许多解码器中使用)转换为一个自定义类型,即字符串类型的 Foo?
英文:
This example will be a little bare to strip out the custom xml parsing that I'm doing, but I've run into this issue:
package main
import (
"encoding/xml"
"fmt"
)
type Foo string
func main() {
var f Foo
var b string
c := xml.CharData{}
f = string(c)
b = string(c)
fmt.Println(b)
}
//prog.go:15: cannot use string(c) (type string) as type Foo in assignment
Foo is a type of string, what am I missing to convert the string representation of xml.CharData (which is valid, use it in many decoders) to a custom type which is a string?
答案1
得分: 4
将 c
直接转换为 Foo
。
f = Foo(c)
Playground: http://play.golang.org/p/WR7gCHm9El
编辑:这样做是因为 Foo
在底层上是一个字符串。Foo
是一个新的、独立的派生类型;它的基本类型是 string
。你可以为任何现有类型创建类似的派生类型。每个派生类型都是独立的,因此你可以获得类型安全性。转换必须是显式的。
英文:
Convert c
to Foo
directly.
f = Foo(c)
Playground: http://play.golang.org/p/WR7gCHm9El
Edit: This works because Foo
is a string underneath. Foo
is a new and distinct derived type; its base type is string
. You can similarly make derived types for any existing type. Each derived type is distinct, so you get type safety. Conversions must be explicit.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论