duanbin4847
duanbin4847
2019-09-11 19:43
浏览 96
已采纳

在Go中使用int和str的数组

I am trying to use an array in Go but I cannot find anything that works with both integers and strings in the same array. I am looking for some documentation that would help me with this problem.

I have it working in Python and I am trying to translate it into Go. Most of the information I found online is showing either arrays of integers or arrays of strings but not both combined.

The integer & string will be passed into another function, depending on the value of the integer determines which string will be concatenated to the string value of the array.

This is an example from Python:

# This is the set arrays
List = [[1, "Pie"], [10, "Fish"], [5, "apples"]]

#This is the code of the function that each array will be passed into
 if list[0] == 1:
        return "There is one " + list[1] + "."
    else:
        return "There are " + str(list[0]) + " " + list[1] + "."

Final Print Output:

There is one Pie.
There are 10 Fish.
There are 5 apples.
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dsjq62428
    dsjq62428 2019-09-11 19:55
    已采纳

    I would recommend going about this like so

    type Foo struct {
      Number int
      Text string
    }
    
      // ...
      array := []Foo{{Number: 1, Text: "pie"}, {Number: 10, Text: "fish"}, {Number: 5, Text: "apples"}}
      if array[0].Number == 1 {
        fmt.Println(array[0].Text)
      }
      // ...
    
    点赞 评论
  • dongshi3361
    dongshi3361 2019-09-11 19:50

    If you really want to do this with arrays only:

    List:=[][]interface{}{ {1,"Pie"}, {10,"Fish"}, {5, "apples"} }
    

    Then, you can do type assertions:

    intValue:=List[0][0].(int)
    strValue:=List[0][1].(string)
    

    However, a better way would be to define a struct containing an int and string member and use an array of that.

    点赞 评论
  • donglian1384
    donglian1384 2019-09-12 15:44

    Using the solution above I was able to get the basics of what I needed.

    
    // The function determines if it's one of or more than 1
    // Giving the correct English sentence
    
    import (
        "fmt"
        "strconv"
    )
    
    type Foo struct {
        Number int
        Text   string
    }
    
    func main() {
        // change the value of fish between 1 and 10 to test the function works as expected
        // List could be pulled in from somewhere else then ran through this function
        array := []Foo{{Number: 1, Text: "pie"}, {Number: 10, Text: "fish"}, {Number: 5, Text: "apples"}}
        for i := 0; i <= 2; i++ {
            n := strconv.Itoa(array[i].Number)
            g := (array[i].Text)
            if array[i].Number == 1 {
                fmt.Println("There is " + n + " " + g + ".")
            } else {
                fmt.Println("There are " + n + " " + g + ".")
            }
        }
    }
    
    点赞 评论

相关推荐