Golang 界面切片
Go lang slice of interface
我正在尝试迭代接口的一部分以通过 id 找到我的特定结构并更改属性。
type A struct {
ID ID
Steps []Step
}
type Step interface{}
type B struct {
ID ID
}
type C struct {
ID ID
}
func (s *A) findStepByID(id ID) (Step, error) {
for index, step := range s.Steps {
switch stepType := step.(type) {
case A:
if stepType.ID == id {
return step, nil
}
case B:
if stepType.ID == id {
return step, nil
}
default:
return nil, errors.New("no step found")
}
}
return nil, errors.New("no step found")
}
当我找到我的结构时 B
然后我将设置 B.ID = xy
函数 findStepByID
returns 一个 interface{}
。如果你想为 ID 分配一个新值,你必须明确地将它转换为一个类型
这里假设您按原样使用 case 来更新结果并使用更新的 value.There 是您可以使用的两种方法
而不是空接口interface{}
使用定义了函数UpdateID(ID)
的接口
使用类型开关,内部开关只进行更新
我不建议第二个,因为它有范围问题
我正在尝试迭代接口的一部分以通过 id 找到我的特定结构并更改属性。
type A struct {
ID ID
Steps []Step
}
type Step interface{}
type B struct {
ID ID
}
type C struct {
ID ID
}
func (s *A) findStepByID(id ID) (Step, error) {
for index, step := range s.Steps {
switch stepType := step.(type) {
case A:
if stepType.ID == id {
return step, nil
}
case B:
if stepType.ID == id {
return step, nil
}
default:
return nil, errors.New("no step found")
}
}
return nil, errors.New("no step found")
}
当我找到我的结构时 B
然后我将设置 B.ID = xy
函数 findStepByID
returns 一个 interface{}
。如果你想为 ID 分配一个新值,你必须明确地将它转换为一个类型
这里假设您按原样使用 case 来更新结果并使用更新的 value.There 是您可以使用的两种方法
而不是空接口
interface{}
使用定义了函数UpdateID(ID)
的接口使用类型开关,内部开关只进行更新
我不建议第二个,因为它有范围问题