Go中不同数组类型的相同方法 [英] Same method on different array types in Go
本文介绍了Go中不同数组类型的相同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我见过一些类似的问题(两种不同的类型如何在使用接口的golang中实现相同的方法?),但在我的情况下,我的类型不具有相同的基类型。
类型十[10]字节
类型二十[20]字节$ b我的类型是不同大小的数组。
$ b func(t * Ten)GetByte0()byte {
return t [0]
}
func(t * Twenty)GetByte0()byte {
return t [0]
}
所以,可能不要重复两种方法GetByte0()?
解决方案
例如,
< pre $
$ b $ 20]字节
类型数字[]字节
func(n数字)GetByte(i int)字节{
return n [i]
}
func main(){
t10:= 10 {10}
fmt.Println(t10)
n10:= Number(t10 [:])
fmt.Println(n10.GetByte(0))
t20:=二十{10,20}
fmt.Println(t20)
fmt.Println(Number(输出:
[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
I've seen some similar questions (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()?
解决方案
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
这篇关于Go中不同数组类型的相同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文