dongyanzhui0524 2017-12-13 00:40
浏览 55

创建根据输入slice参数执行不同操作的函数

I just started to learn Go language and I want to build a function which will be selecting a random subsequence from a slice. However, I don't know what type of values this slice can store, these can be integers, strings or elements of some struct. For example, let's assume I have to structures:

type person struct {
    name string
    age  int
}

type animal struct {
    name  string
    age   int
    breed string
}

Now, I want to build function getRandomSequence as follows: given as arguments a slice S and a length l the function returns a slice which contains l randomly selected elements from slice S. The problem which I encountered was - how to make this function work for any possible slice. I tried to do the following:

func GetRandomSequence(S interface{}, l int) []interface{} {
   switch S.(type) {
   case person:
      // Do random selection of l elements from S and return them
   case animal:
      // Do random selection of l elements from S and return them
   case int:
     // Do random selection of l elements from S and return them
   }
   return " Not Recognised"
}

Can someone suggest how I can write such function? I manage to make similar (i.e., general) functions work if S would be a single element of any type (so instead of []interface{} would be just interface{}) but I cannot find out how to solve this problem.

  • 写回答

2条回答 默认 最新

  • duanbigan7765 2017-12-13 00:45
    关注

    Just use interface{} not []interface{}. An empty interface can store any type, including slices.

    Your code would look something like this (although I didn't test):

    func GetRandomSequence(S interface{}, l int) interface{} {
       returnSlice := []interface{}
       switch v := s.(type) {
       // inside the switch v has the value of S converted to the type
       case []person:
          // v is a slice of persons here
       case []animal:
          // v is a slice of animals here
       case []int:
          // v is a slice of ints here
       case default:
           // v is of type interface{} because i didn't match any type on the switch
           // I recommend you return nil on error instead of a string
           // or always return 2 things, the value and an error like 
           // the standard library
           return "Not Recognized" 
       }
       rerurn returnSlice
    }
    

    I recommend you do the complete Tour of go, but for this question the answer is here.

    Depending on what you want to do exactly, it looks like you might not need different types of slices but a slice of interface{}. If in your function to extract random elements from the slice you don't care about the type of the elements just do:

    func GetRandomSequence(S []interface{}, l int) []interface{} {
        returnSlice := make([]interface{}, 0, l)
        for i:=0; i<l; i++ { 
            // S[i] here is always of type interface{}
            returnSlice = append(returnSlice, S[getRnd()]) // you need to implement getRnd() or just "math/rand" or something.
        }
        return returnSlice 
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条