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

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

如何在 Go 中創建一個變量類型的切片?

如何在 Go 中創建一個變量類型的切片?

Go
侃侃無極 2022-03-07 22:52:50
我有一個功能。func doSome(v interface{}) {}  如果我通過指針將結構切片傳遞給函數,則函數必須填充切片。type Color struct {}type Brush struct {}var c []ColordoSome(&c) // after с is array contains 3 elements type Colorvar b []BrushdoSome(&b) // after b is array contains 3 elements type Brush也許我需要使用反射,但是如何?
查看完整描述

3 回答

?
MM們

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

func doSome(v interface{}) {


    s := reflect.TypeOf(v).Elem()

    slice := reflect.MakeSlice(s, 3, 3)

    reflect.ValueOf(v).Elem().Set(slice)


}  


查看完整回答
反對 回復 2022-03-07
?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

類型開關??!


package main

import "fmt"


func doSome(v interface{}) {

  switch v := v.(type) {

  case *[]Color:

    *v = []Color{Color{0}, Color{128}, Color{255}}

  case *[]Brush:

    *v = []Brush{Brush{true}, Brush{true}, Brush{false}}

  default:

    panic("unsupported doSome input")

  }

}  


type Color struct {

    r uint8

}

type Brush struct {

    round bool

}


func main(){

    var c []Color

    doSome(&c) // after с is array contains 3 elements type Color


    var b []Brush

    doSome(&b) // after b is array contains 3 elements type Brush


    fmt.Println(b)

    fmt.Println(c)


}


查看完整回答
反對 回復 2022-03-07
?
忽然笑

TA貢獻1806條經驗 獲得超5個贊

Go 沒有泛型。你的可能性是:


接口調度


type CanTraverse interface {

    Get(int) interface{}

    Len() int

}

type Colours []Colour


func (c Colours) Get(i int) interface{} {

    return c[i]

}

func (c Colours) Len() int {

    return len(c)

}

func doSome(v CanTraverse) {

    for i := 0; i < v.Len; i++ {

        fmt.Println(v.Get(i))

    }

}

按照@Plato 的建議輸入 switch


func doSome(v interface{}) {

  switch v := v.(type) {

  case *[]Colour:

    //Do something with colours

  case *[]Brush:

    //Do something with brushes

  default:

    panic("unsupported doSome input")

  }

}

像 fmt.Println() 一樣進行反射。反射非常強大但非常昂貴,代碼可能很慢。最小的例子


func doSome(v interface{}) {

    value := reflect.ValueOf(v)

    if value.Kind() == reflect.Slice {

        for i := 0; i < value.Len(); i++ {

            element := value.Slice(i, i+1)

            fmt.Println(element)

        }

    } else {

        fmt.Println("It's not a slice")

    }

}


查看完整回答
反對 回復 2022-03-07
  • 3 回答
  • 0 關注
  • 193 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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