duanhuhong5255 2015-03-04 19:44
浏览 77
已采纳

将Go结构转换为字符串

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条回答 默认 最新

  • dporu02280 2015-03-04 20:16
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line