我是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
出现"不适用
"的提示信息。在代码的另一个版本中,我认为提示信息是"索引超出范围
"。
*Location
传递给Merge
,这就是为什么会出现 "Not Applicable" 的原因。此外,你可能想考虑为你的类型实现fmt.Stringer
。 - user142162servicesA.Users[0].Location
的类型是什么:Location
还是*Location
?同时,您可能会发现在Sprintf
中使用%v
或%+v
很有用。 - kostya