Go 如何从用作泛型的接口访问struct属性
也许我的代码过于复杂,但我正试图更好地理解接口和结构在golang中的工作方式 基本上,我将满足接口i的元素存储在哈希表中。由于所有满足I的项都可以包含在I元素中,我想我可以使用I作为一种通用接口,将它们填充到hashmap中,然后稍后将它们拉出并从那里访问underlyng struct method 不幸的是,在拉出元素之后,我发现我无法调用struct方法,因为元素是接口类型,并且原始结构不再可访问 有没有一种方法可以获得对结构的干净、简单的访问,从而满足I 这是我的代码,它抛出一个值。名称未定义类型我在for循环中没有字段或方法名称:Go 如何从用作泛型的接口访问struct属性,go,Go,也许我的代码过于复杂,但我正试图更好地理解接口和结构在golang中的工作方式 基本上,我将满足接口i的元素存储在哈希表中。由于所有满足I的项都可以包含在I元素中,我想我可以使用I作为一种通用接口,将它们填充到hashmap中,然后稍后将它们拉出并从那里访问underlyng struct method 不幸的是,在拉出元素之后,我发现我无法调用struct方法,因为元素是接口类型,并且原始结构不再可访问 有没有一种方法可以获得对结构的干净、简单的访问,从而满足I 这是我的代码,它抛出一个值。名
/**
* Define the interface
*/
type I interface{
test()
}
/**
* Define the struct
*/
type S struct{
name string
}
/**
* S now implements the I interface
*/
func (s S) test(){}
func main(){
/**
* Declare and initialize s S
*/
s := S{name:"testName"}
/**
* Create hash table
* It CAN contains S types as they satisfy I interface
* Assign and index to s S
*/
testMap := make(map[string]I)
testMap["testIndex"] = s
/**
* Test the map length
*/
fmt.Printf("Test map length: %d\r\n", len(testMap))
for _, value := range testMap{
/**
* This is where the error is thrown, value is of Interface type, and it is not aware of any "name" property
*/
fmt.Printf("map element name: %s\r\n", value.name)
}
}
您应该向接口添加访问器:
type I interface {
test()
Name() string
}
然后确保结构实现此方法:
func (s S) Name() string {
return s.name
}
然后使用访问器方法访问名称:
fmt.Printf("map element name: %s\r\n", value.Name())
您应该向接口添加访问器:
type I interface {
test()
Name() string
}
然后确保结构实现此方法:
func (s S) Name() string {
return s.name
}
然后使用访问器方法访问名称:
fmt.Printf("map element name: %s\r\n", value.Name())
我想你需要的是如中所示的类型开关
您可以访问底层结构,如下所示:
for _, value := range testMap {
switch v := value.(type) {
case S:
fmt.Printf("map element name: %s\r\n", v.name)
// TODO: add other types here
}
}
我想你需要的是如中所示的类型开关
您可以访问底层结构,如下所示:
for _, value := range testMap {
switch v := value.(type) {
case S:
fmt.Printf("map element name: %s\r\n", v.name)
// TODO: add other types here
}
}
我认为这是处理接口可能变成的多个值的一个好方法。我仍然认为访问器方法更干净,但这更灵活imho@AndreaGolin是的,这取决于你将如何访问这些值。我认为这是处理接口可能变成的多个值的一个好方法。我仍然认为访问器方法更干净,但这更灵活imho@AndreaGolin是的,这取决于您将如何访问这些值。