将字符串转换为Foo(类型为字符串)

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

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.

huangapple
  • 本文由 发表于 2014年11月21日 01:25:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/27045769.html
匿名

发表评论

匿名网友

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

确定