Go语言切片(slice)的接口(interface)

huangapple go评论74阅读模式
英文:

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("未找到步骤")
        }
    }
    return nil, errors.New("未找到步骤")
}

当我找到我的结构体,例如 B,然后我将设置 B.ID = xy

英文:

I am trying to iterate over a slice of interfaces to find my specific struct by id and change the attribute.

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")
}

When I found my struct for example B then I will set B.ID = xy

答案1

得分: 1

函数findStepByID返回一个interface{}类型。如果你想给ID赋一个新值,你必须显式地将其转换为某种类型。

假设你使用的是原样例来更新结果并使用更新后的值,有两种方法可以实现:

  1. 不要使用空接口interface{},而是使用一个带有定义了UpdateID(ID)函数的接口。

  2. 使用类型切换,在切换内部进行更新操作。

我不建议使用第二种方法,因为它存在作用域问题。

英文:

The function findStepByID returns an interface{} .If you want to assign ID with a new value you have to explicitly cast it to a type

Here assuming you use case as is to update the result and use updated value.There are two ways you may do it

  1. Instead of a empty interfaceinterface{} use a interface with function UpdateID(ID) defined

  2. Use a type switch and inside switch only do the update

I would not suggest second one as it has scope problems

huangapple
  • 本文由 发表于 2017年2月10日 20:27:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/42159412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定