在Go语言中,可以使用相同的方法来处理不同的数组类型。

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

Same method on different array types in Go

问题

我看到了一些类似的问题(https://stackoverflow.com/questions/31505587/how-can-two-different-types-implement-the-same-method-in-golang-using-interfaces),但在我的情况下,我的类型没有相同的基本类型。我的类型是不同大小的数组。

  1. type Ten [10]byte
  2. type Twenty [20]byte
  3. func (t *Ten) GetByte0() byte {
  4. return t[0]
  5. }
  6. func (t *Twenty) GetByte0() byte {
  7. return t[0]
  8. }

那么,有可能不重复定义这两个方法 GetByte0() 吗?

英文:

I've seen some similar questions (https://stackoverflow.com/questions/31505587/how-can-two-different-types-implement-the-same-method-in-golang-using-interfaces), but in my case my types do not have the same base type. My types are arrays of different sizes.

  1. type Ten [10]byte
  2. type Twenty [20]byte
  3. func (t *Ten) GetByte0() byte {
  4. return t[0]
  5. }
  6. func (t *Twenty) GetByte0() byte {
  7. return t[0]
  8. }

So, it's possible don't to repeat the two methods GetByte0()?

答案1

得分: 1

例如,

  1. package main
  2. import "fmt"
  3. type Ten [10]byte
  4. type Twenty [20]byte
  5. type Number []byte
  6. func (n Number) GetByte(i int) byte {
  7. return n[i]
  8. }
  9. func main() {
  10. t10 := Ten{10}
  11. fmt.Println(t10)
  12. n10 := Number(t10[:])
  13. fmt.Println(n10.GetByte(0))
  14. t20 := Twenty{10, 20}
  15. fmt.Println(t20)
  16. fmt.Println(Number(t20[:]).GetByte(1))
  17. }

输出:

  1. [10 0 0 0 0 0 0 0 0 0]
  2. 10
  3. [10 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  4. 20
英文:

For example,

  1. package main
  2. import "fmt"
  3. type Ten [10]byte
  4. type Twenty [20]byte
  5. type Number []byte
  6. func (n Number) GetByte(i int) byte {
  7. return n[i]
  8. }
  9. func main() {
  10. t10 := Ten{10}
  11. fmt.Println(t10)
  12. n10 := Number(t10[:])
  13. fmt.Println(n10.GetByte(0))
  14. t20 := Twenty{10, 20}
  15. fmt.Println(t20)
  16. fmt.Println(Number(t20[:]).GetByte(1))
  17. }

Output:

  1. [10 0 0 0 0 0 0 0 0 0]
  2. 10
  3. [10 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  4. 20

huangapple
  • 本文由 发表于 2017年4月30日 06:16:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/43700989.html
匿名

发表评论

匿名网友

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

确定