我剛開始學習 Go 并且有一個關于定義可能是兩種型別之一的引數的問題。拿代碼:
type Thing struct {
a int
b int
c string
d string
}
type OtherThing struct {
e int
f int
c string
d string
}
func doSomething(t Thing/OtherThing) error {
fmt.println(t.d)
return nil
}
由于結構沒有功能,我目前無法為它們撰寫介面。那么這里的 Go 慣用做法是什么?是否只是將隨機函式系結到結構并撰寫介面或其他東西?
謝謝您的幫助...
uj5u.com熱心網友回復:
為這兩種型別宣告一個具有通用功能的介面。使用介面型別作為引數型別。
// Der gets d values.
type Der interface {
D() string
}
type Thing struct {
a int
b int
c string
d string
}
func (t Thing) D() string { return t.d }
type OtherThing struct {
e int
f int
c string
d string
}
func (t OtherThing) D() string { return t.d }
func doSomething(t Der) error {
fmt.Println(t.D())
return nil
}
uj5u.com熱心網友回復:
您可以通過從基本結構中組合它們來為兩個結構提供一些共享功能:
package main
import (
"fmt"
)
// Der gets d values.
type Der interface {
D() string
}
type DBase struct {
d string
}
func (t DBase) D() string { return t.d }
type Thing struct {
DBase
a int
b int
c string
}
type OtherThing struct {
DBase
e int
f int
c string
}
func doSomething(t Der) error {
fmt.Println(t.D())
return nil
}
func main() {
doSomething(Thing{DBase: DBase{"hello"}})
doSomething(OtherThing{DBase: DBase{"world"}})
}
DBase提供欄位(d),并滿足Der介面兩者以相同的方式Thing和OtherThing。它確實使結構文字的定義時間更長一些。
uj5u.com熱心網友回復:
您可以使用interface{}引數和反射包來訪問公共欄位。很多人會說這個方法不習慣。
func doSomething(t interface{}) error {
d := reflect.ValueOf(t).FieldByName("d").String()
fmt.Println(d)
return nil
}
在操場上嘗試一個例子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/347814.html
上一篇:golang快速替代memcpy
