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

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

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),但在我的情况下,我的类型没有相同的基本类型。我的类型是不同大小的数组。

type Ten [10]byte
type Twenty [20]byte

func (t *Ten) GetByte0() byte {
    return t[0]
}

func (t *Twenty) GetByte0() byte {
    return t[0]
}

那么,有可能不重复定义这两个方法 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.

type Ten [10]byte
type Twenty [20]byte

func (t *Ten) GetByte0() byte {
    return t[0]
}

func (t *Twenty) GetByte0() byte {
    return t[0]
}

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

答案1

得分: 1

例如,

package main

import "fmt"

type Ten [10]byte

type Twenty [20]byte

type Number []byte

func (n Number) GetByte(i int) byte {
    return n[i]
}

func main() {
    t10 := Ten{10}
    fmt.Println(t10)
    n10 := Number(t10[:])
    fmt.Println(n10.GetByte(0))

    t20 := Twenty{10, 20}
    fmt.Println(t20)
    fmt.Println(Number(t20[:]).GetByte(1))
}

输出:

[10 0 0 0 0 0 0 0 0 0]
10
[10 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
20
英文:

For example,

package main

import "fmt"

type Ten [10]byte

type Twenty [20]byte

type Number []byte

func (n Number) GetByte(i int) byte {
	return n[i]
}

func main() {
	t10 := Ten{10}
	fmt.Println(t10)
	n10 := Number(t10[:])
	fmt.Println(n10.GetByte(0))

	t20 := Twenty{10, 20}
	fmt.Println(t20)
	fmt.Println(Number(t20[:]).GetByte(1))
}

Output:

[10 0 0 0 0 0 0 0 0 0]
10
[10 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
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:

确定