douping1581 2015-12-10 21:17
浏览 193

从字符串列表转换为go中的接口列表

I want to pass in a list of strings as generic parameters in go, but not sure if its possible. I have workarounds but feel like I'm just not able to get syntax correct.

package main

import "fmt"

func Set(otherFields ...interface{}) {
  fmt.Printf("%v", otherFields)
}

func main() {
  a := []string {"Abc", "def", "ghi"}
  Set(a)  // incorrect behavior because a passed through as a list, rather than a bunch of parameters 
//   Set(a...)  // compiler error: cannot use a (type []string) as type []interface {} in argument to Set
//  Set([]interface{}(a)) // compiler error: cannot convert a (type []string) to type []interface {}
  // This works but I want to do what was above.
  b := []interface{} {"Abc", "def", "ghi"}
  Set(b...)
}
  • 写回答

1条回答 默认 最新

  • dousha4804 2015-12-10 21:21
    关注

    You have to deal with each string individually. You can't just cast the whole collection. Here's an example;

    package main
    
    import "fmt"
    
    func main() {
      a := []string {"Abc", "def", "ghi"}
      b := []interface{}{} // initialize a slice of type interface{}
    
      for _, s := range a {
         b = append(b, s) // append each item in a to b
      }
      fmt.Println(len(b)) // prove we got em all
    
      for _, s := range b {
        fmt.Println(s) // in case you're real skeptical
      }
    
    }
    

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

    As you can see, no cast is necessary because the collection of type inferface{} will accept any type (all types implement the empty interface Go equivalent of a void pointer in C). But you do have to deal with each item in collection individually.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题