将Go结构体转换为字符串

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

Converting Go struct to string

问题

我的代码:

type Link struct {
    Href string `xml:"href,attr"`
}

var html string = ""
func (s Entry) String() string {
    links := s.Link.Href
}

我解析了整个 XML 文档以获取链接和文本,现在我想将所有解析的数据追加到 html 变量中,以在本地主机上构建一个漂亮的视图。但是 s.Link 无法转换为字符串数据类型,可能是因为类型转换只支持基本数据类型。有什么解决方案吗?

演示链接:http://play.golang.org/p/7HRHusXLe2

英文:

My Code :

type Link struct {
	Href string `xml:"href,attr"`
}

var html Link = ""
func (s Entry) String() string {
  links := string(s.Link)
}

I parsed a whole XML document to get the links and text, Now I want to append all the parsed data in html variable to construct a nice view on the localhost. But s.Link can't be converted to string data type maybe because type conversion only supports basic data-types , Any Solutions ?

Live demo : http://play.golang.org/p/7HRHusXLe2

答案1

得分: 2

在你的情况下,你不需要附加结构体Linkstring表示,你只需要它的Href字段,该字段已经是string类型。

func (s Entry) LinkString() string {
    return s.Link.Href
}

另外请注意,如果你使用非指针接收器Entry,你的方法LinkString()将接收到结构体的副本。在这种情况下并不是问题,只是稍微慢一些,因为需要进行复制。

如果你的结构体变得更大,最好使用指针接收器:*Entry

func (s *Entry) LinkString() string {
    return s.Link.Href
}

还要注意的是,你甚至不需要一个方法来访问URL文本,因为你的字段(Entry.LinkLink.Href)是公开的,因为它们以大写字母开头,所以你可以像这样引用它:

// e 是 Entry 类型:
url := e.Link.Href
// url 是 string 类型
英文:

In your case you don't want to append the string representation of the struct Link, you just need its Href field which is already of type string.

func (s Entry) LinkString() string {
    return s.Link.Href
}

Also note that if you use a non-pointer receiver Entry, your method LinkString() will receive a copy of the struct. Which in this case is not a problem, it's just a little slower because a copy has to be made.

If your struct gets bigger, it's better to use pointer receiver: *Entry:

func (s *Entry) LinkString() string {
    return s.Link.Href
}

Also note that you don't even need a method to access the URL text because your fields (Entry.Link and Link.Href) are exported because they start with an upper-case letter, so you can simply refer to it like this:

// e is of type Entry:
url := e.Link.Href
// url is of type string

huangapple
  • 本文由 发表于 2015年3月5日 03:44:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/28863473.html
匿名

发表评论

匿名网友

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

确定