第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何為接口設置任何值{}

如何為接口設置任何值{}

Go
BIG陽 2021-05-02 13:49:52
我有以下代碼:package mainimport (   "fmt")type Point struct {    x,y int}func decode(value interface{}) {    fmt.Println(value) // -> &{0,0}    // This is simplified example, instead of value of Point type, there    // can be value of any type.    value = &Point{10,10}}func main() {    var p = new(Point)    decode(p)    fmt.Printf("x=%d, y=%d", p.x, p.y) // -> x=0, y=0, expected x=10, y=10}我想將任何類型的值設置為傳遞給decode函數(shù)的值。在Go中有可能,還是我誤會了某些東西?http://play.golang.org/p/AjZHW54vEa
查看完整描述

2 回答

?
慕妹3242003

TA貢獻1824條經(jīng)驗 獲得超6個贊

通常,僅使用反射

package main


import (

    "fmt"

    "reflect"

)


type Point struct {

    x, y int

}


func decode(value interface{}) {

    v := reflect.ValueOf(value)

    for v.Kind() == reflect.Ptr {

        v = v.Elem()

    }

    n := reflect.ValueOf(Point{10, 10})

    v.Set(n)

}


func main() {

    var p = new(Point)

    decode(p)

    fmt.Printf("x=%d, y=%d", p.x, p.y)

}


查看完整回答
反對 回復 2021-05-17
?
開心每一天1111

TA貢獻1836條經(jīng)驗 獲得超13個贊

我不確定您的確切目標。


如果您想斷言這value是指向Point它的指針并進行更改,則可以執(zhí)行以下操作:


func decode(value interface{}) {

    p := value.(*Point)

    p.x=10

    p.y=10

}


查看完整回答
反對 回復 2021-05-17
  • 2 回答
  • 0 關(guān)注
  • 207 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號