我有一个脚本从不同的数据源提取,这取决于用户输入的一般界面和每个数据源的类型。然后,每个数据源都有一个方法来获取该特定源的元数据。我正在努力理解的input实现,以根据输入切换类型。
这个例子没有编译,但是它最能说明我想要做的事情:
type Post interface {
GetMetadata() bool
}
type YouTubeVideo struct {
ID string
Title string
ChannelID string
ChannelTitle string
PublishedAt string
}
func (ig *YouTubeVideo) GetMetadata() bool {
// ...
}
type InstagramPic struct {
ID string
ShortCode string
Type string
Title string
PublishedAt string
}
func (ig *InstagramPic) GetMetadata() bool {
// ...
}
func main() {
var thePost Post
switch domain {
case "youtube":
thePost = new(YouTubeVideo)
thePost.ID = pid
case "instagram":
thePost = new(InstagramPic)
thePost.ShortCode = pid
}
thePost.GetMetadata()
fmt.Println(thePost.title)
}发布于 2015-04-07 12:35:51
根据细节,我相信你的结构总体上是健全的。但还需要更多的理解。
使用接口(如Post ),您只能访问为接口定义的方法(在本例中为GetMetadata())。存储在接口中的值,例如。如果没有*YouTubeVideo或类型开关,则无法访问类型断言或类型开关。
因此,不可能使用thePost.title获得标题。
获取Post字段值
这里有两个选项(如果算上“类型断言”,则有三个):
1)通过接口方法添加对属性的访问
type Post interface {
GetMetadata() bool
Title() string // Added Title method
}
func (ig *YouTubeVideo) Title() string {
return ig.Title
}
...
fmt.Println(thePost.Title())2)使用类型开关访问属性
switch v := thePost.(type) {
case *YouTubeVideo:
fmt.Println(v.ChannelTitle)
case *InstagramPic:
fmt.Println(v.PublishedAt)
}如果实现Post的所有类型也应该授予对某个属性的访问权限,则选择1)是非常有用的。( 2)允许您访问特定于该类型的字段,但它需要为每种类型设置一个大小写。
设置Post字段值
就像获取时一样,您不能直接设置接口值的字段。在这种情况下,您应该先设置所需的字段,然后再将其存储在接口中:
v := new(YouTubeVideo)
v.ID = pid
thePost = v // Store the *YouTubeVideo in thePost或者更短一点:
thePost = &YouTubeVideo{ID: pid}最后注
通过一些调优,您的结构应该使用接口和类型开关工作。但确切地说,如何构造它取决于你的具体情况,而我们对此了解太少。
为了更好地理解如何使用接口,我建议阅读:有效Go:接口和类型
https://stackoverflow.com/questions/29482343
复制相似问题