Go中不同数组类型的相同方法

时间:2017-04-29 22:16:55

标签: go

我见过一些类似的问题(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()?

1 个答案:

答案 0 :(得分: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
相关问题