Why is "if s, ok := it.(TaggerShape); ok {" and "else if s, ok := it.(TaggerShape); ok {" in the same function?

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

Why is "if s, ok := it.(TaggerShape); ok {" and "else if s, ok := it.(TaggerShape); ok {" in the same function?

问题

这段代码重复调用了相同的函数两次,这是因为我对Go语言还不太熟悉,所以很可能是我的误解。


func Tag(it Shape, tag string) Shape {
	if s, ok := it.(TaggerShape); ok {
		s.AddTags(tag)
		return s
	} else if s, ok := it.(TaggerShape); ok {
		s.AddTags(tag)
		return s
	}
	return NewSave(it, tag)
}

这段代码的作用是给形状对象添加标签。如果形状对象实现了TaggerShape接口,就调用AddTags方法并返回该对象。否则,如果形状对象实现了TaggerShape接口,同样调用AddTags方法并返回该对象。如果都不满足,则调用NewSave函数创建一个新的保存对象并返回。

这段代码的来源是:https://github.com/cayleygraph/cayley/blob/275a7428fb10fdb4d1167f09a7120898239903dd/graph/iterator/save.go#L14-L23

英文:

Isn't this code repeating the same call twice? I am new to go, so this is most likely my own misunderstanding.


func Tag(it Shape, tag string) Shape {
	if s, ok := it.(TaggerShape); ok {
		s.AddTags(tag)
		return s
	} else if s, ok := it.(TaggerShape); ok {
		s.AddTags(tag)
		return s
	}
	return NewSave(it, tag)
}

It is from here: https://github.com/cayleygraph/cayley/blob/275a7428fb10fdb4d1167f09a7120898239903dd/graph/iterator/save.go#L14-L23

答案1

得分: 1

是的,它是重复的。你可以移除else if块:

func Tag(it Shape, tag string) Shape {
    if s, ok := it.(TaggerShape); ok {
        s.AddTags(tag)
        return s
    }

    return NewSave(it, tag)
}

所以你知道it.(TaggerShape)的含义,来自规范:

对于一个接口类型的表达式x和类型T,主表达式x.(T)断言x不是nil,并且存储在x中的值是类型T。x.(T)的表示法称为类型断言。

更准确地说,如果T不是接口类型,x.(T)断言x的动态类型与类型T相同。在这种情况下,T必须实现x的(接口)类型;否则,类型断言是无效的,因为x不可能存储类型T的值。如果T是接口类型,x.(T)断言x的动态类型实现了接口T。

英文:

Yes, it's duplicated. You can remove the else if block:

func Tag(it Shape, tag string) Shape {
    if s, ok := it.(TaggerShape); ok {
        s.AddTags(tag)
        return s
    }

    return NewSave(it, tag)
}

So just you know what it.(TaggerShape) means, from the spec:

> For an expression x of interface type and a type T, the primary
> expression
>
> x.(T) asserts that x is not nil and that the value stored in x is of
> type T. The notation x.(T) is called a type assertion.
>
> More precisely, if T is not an interface type, x.(T) asserts that the
> dynamic type of x is identical to the type T. In this case, T must
> implement the (interface) type of x; otherwise the type assertion is
> invalid since it is not possible for x to store a value of type T. If
> T is an interface type, x.(T) asserts that the dynamic type of x
> implements the interface T.

huangapple
  • 本文由 发表于 2022年3月17日 08:05:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/71505620.html
匿名

发表评论

匿名网友

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

确定