In the Go language function parameter transfer

Asked 1 years ago, Updated 1 years ago, 106 views

type Brand struct {
    Idx  string `json:"idx"`
    Code int    `json:"code"`
    Name string `json:"name"`
}
brands := make([]*Brand, 0)
r.DB.Raw(query).Scan(&brands)

DB data is added to the brands variable with the above structure You want to create an array-type structure and pass it as a function.

func Test(brands interface{}){
  for i := range brands {
    fmt.Println(brands[i])
  }
}

There's a way to specify the structure directly here, but... It's an example What I'm trying to do is I don't know what type of structure is coming I want to use a repetitive statement of an array structure that is passed over as a function, but the brands are in the interface form I can't execute repeat statement...

func Test(brands []interface{}){
  for i := range brands {
    fmt.Println(brands[i])
  }
}

If you write as above, an error appears when passing the parameter. Cannot use 'brands' (type []*model.Brand) as type []interface{}

go function parameter args

2022-09-21 11:10

3 Answers

package main

import "fmt"

func Test(brands []interface{}){
  for i := range brands {
    fmt.Println(brands[i])
  }
}

type Brand struct {
    Idx  string
    Code int
    Name string
}

func main() {
    parsed := []Brand{Brand{"1", 1, "one"}, Brand{"2", 2, "two"}}
    brands := make([]interface{}, len(parsed))
    for i, v := range parsed {
        brands[i] = v
    }
    Test(brands)
}

https://golang.org/doc/faq#convert_slice_of_interface https://stackoverflow.com/questions/27689058/convert-string-to-interface


2022-09-21 11:10

Let me introduce two main ways.

1. Type Assertion

func Test(brands interface{}) {
    brandsSlice, ok := brands.([]interface{})
    if !ok {
        // // error
    }
    for i := range brandsSlice {
        fmt.Println(brandsSlice[i])
    }
}

This is how to check if the factor is slice and then do what you want.

2. reflect

func Test(brands interface{}) {
    switch reflect.TypeOf(brands).Kind() {
    case reflect.Slice:
        value := reflect.ValueOf(brands)
        for i := 0; i < value.Len(); i++ {
            fmt.Println(value.Index(i))
        }
    }
}

The second method is to write reflect. You must import reflect for this method.


2022-09-21 11:10

How do I leave a question here?


2022-09-21 11:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.