英文:
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
在你的情况下,你不需要附加结构体Link
的string
表示,你只需要它的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.Link
和Link.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论