【发布时间】:2015-08-31 16:30:12
【问题描述】:
我是 golang 新手,我正在尝试创建一个函数,根据它所使用的结构,将使用 Sprintf 返回格式化字符串
type Name struct {
Title string
First string
Last string
}
type Location struct {
Street string
City string
State string
Zip string
}
func Merge(m interface{}) string {
switch m.(type) {
case *Location:
return fmt.Sprintf("%s \n %s, %s %s", m.(*Location).Street, m.(*Location).City, m.(*Location).State, m.(*Location).Zip)
case *Name:
return fmt.Sprintf("%s. %s %s", m.(*Name).Title, m.(*Name).First, m.(*Name).Last)
}
return "Not Applicable"
}
fmt.Println(Merge(Location))
我收到了来自我的PrintLn 的“Not Applicable”消息。在代码的一个版本中,我相信消息是“out of index”。
【问题讨论】:
-
您没有将
*Location传递给Merge;这就是为什么你得到“不适用”的原因。此外,您可能需要考虑为您的类型实现fmt.Stringer。 -
感谢蒂姆的建议。您能否详细说明我将如何使用 fmt.Stringer? println(merge())) 行是我所拥有的简化。我的实际线路是 fmt.Println(Merge(servicesA.Users[0].Location))
-
servicesA.Users[0].Location的类型是什么:Location或*Location?此外,您可能会发现有用的%v或%+v和Sprintf -
感谢您的评论,科斯蒂亚。它应该只是位置。当我尝试删除函数中的指针(*Location to Location)并运行它时,我得到了这个:panic: interface conversion: interface is main.Location not *main.Location
标签: struct go interface switch-statement