亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang 泛型 - 簡單用例

Golang 泛型 - 簡單用例

Go
人到中年有點甜 2023-05-15 10:36:22
假設我有 3 個結構:type A struct{   Foo map[string]string}type B struct{   Foo map[string]string}type C struct{   Foo map[string]string}然后我想創建一個可以接受任何這些結構的函數:func handleFoo (){}有什么辦法可以用 Golang 做到這一點嗎?就像是:type ABC = A | B | Cfunc handleFoo(v ABC){   x: = v.Foo["barbie"] // this would be nice!}好的,讓我們嘗試一個界面:type FML interface {  Bar() string}func handleFoo(v FML){   z := v.Bar() // this will compile   x: = v.Foo["barbie"] // this won't compile - can't access properties like Foo from v}在一種鼓勵/強制組合的語言中,我不明白為什么你不能訪問像 Foo 這樣的屬性。
查看完整描述

3 回答

?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

您可以以這種方式使用接口,添加一個方法GetFoo來獲取每個結構的 foo。


type A struct{

    Foo map[string]string

}


func(a *A) GetFoo() map[string]string {

    return a.Foo

}


type B struct{

    Foo map[string]string

}


func(b *B) GetFoo() map[string]string {

    return b.Foo

}


type C struct{

    Foo map[string]string

}


func(c *C) GetFoo() map[string]string {

    return c.Foo

}


type ABC interface {

    GetFoo() map[string][string]

}


func handleFoo (v ABC){

    foo := v.GetFoo()

    x:=foo["barbie"]

}


查看完整回答
反對 回復 2023-05-15
?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

因為 A、B 和 C 都可分配給相同的底層類型,所以您可以使用帶有該底層類型參數的函數:func handleFoo(v struct{ Foo map[string]string })

在操場上運行它。

這種方法的一個限制是 A、B 和 C 上的方法(即使具有相同的名稱和簽名)在handleFoo.


查看完整回答
反對 回復 2023-05-15
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

你可以嘗試reflect傳遞interface{}handleFoo

https://play.golang.org/p/sLyjDvVrUjQ

https://golang.org/pkg/reflect/

package main


import (

    "fmt"

    "reflect"

)


func main() {

    type A struct {

        Foo map[string]string

    }

    type B struct {

        Foo map[string]int

    }

    type C struct {

        Foo map[string]uint

    }

    a := A{

        Foo: map[string]string{"a":"1"},

    }


    b := B{

        Foo: map[string]int{"a":2},

    }


    c := C {

        Foo: map[string]uint{"a":3},

    }



    fmt.Println(a, b, c)


    handleFoo(a)

    handleFoo(b)

    handleFoo(c)


    fmt.Println(a, b, c)

}




func handleFoo(s interface{}) {

    v := reflect.ValueOf(s)

    foo := v.FieldByName("Foo")

    if !foo.IsValid(){

        fmt.Println("not valid")

        return

    }


    switch foo.Type() {

    case reflect.TypeOf(map[string]string{}):

        fmt.Println("is a map[string]string")

        foo.Interface().(map[string]string)["a"] = "100"

    case reflect.TypeOf(map[string]int{}):

        fmt.Println("is a map[string]int")

        foo.Interface().(map[string]int)["a"] =  200

    case reflect.TypeOf(map[string]uint{}):

        fmt.Println("is a map[string]uint")

        foo.Interface().(map[string]uint)["a"] =  300

    }

}


查看完整回答
反對 回復 2023-05-15
  • 3 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號