douqiu1604 2019-03-12 04:20
浏览 65

将int []传递给函数,但函数返回空数组

I am passing in a string array and an empty integer array into a function. The point of the function is to convert each element of the string array to an integer and store that into the integer array. When I print the integer array from within the function itself, everything is fine. However, when I try to print the integer array outside of the function, it prints an empty array.

employeeDataInt is the integer array, and employeeDataString is the string array.

I apologize if this is a dumb question but I am new to go. Thanks

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strconv"
    "strings"
)

func strToInt(employeeDataString []string, emplyoeeDataInt []int) []int {
    for _, i := range employeeDataString[2:] {
        j, err := strconv.Atoi(i)
        if err != nil {
            panic(err)
        }
        employeeDataInt = append(employeeDataInt, j)
        fmt.Println(employeeDataInt) //this prints out the appropriate array

    }
    return employeeDataInt
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter file name: ")
    fileName, err := reader.ReadString('
')
    if err != nil {
        log.Fatalf("failed opening file: %s", err)
    }
    fileName = strings.TrimSuffix(fileName, "
")

    file, err := os.Open(fileName)
    scanner := bufio.NewScanner(file)
    scanner.Split(bufio.ScanLines)
    var employeeLine []string

    for scanner.Scan() {
        employeeLine = append(employeeLine, scanner.Text())
    }

    file.Close()
    var employeeDataString = []int{}
    for _, employee := range employeeLine {
        employeeDataString := strings.Split(employee, " ")

        strToInt(employeeDataString, employeeDataInt)
        fmt.Println(playerData2) //this is outputting just `[]`

    }
}
  • 写回答

2条回答 默认 最新

  • dongmei1911 2019-03-12 07:02
    关注

    You aren't taking the value of the array and thus the Slice you passed into the function might or might not be updated correctly.

    strToInt(employeeDataString, employeeDataInt)
    // should be
    employeeDataInt = strToInt(employeeDataString, employeeDataInt)
    

    And while at it, you are never assigning playerData2. So fmt.Println(playerData2) will always be [].

    But aside from that there are some subtle issues with your usage of Arrays/Slices here:

    First the difference between Slices and Arrays:

    Go does not allow you to directly work with Arrays. Unless they have a fixed length ([3]int{} or []int{1,2,3]) you aren't actually looking at an array but at a Slice ([]int).

    The slice is just a pointer to an array (along with it's capacity and some other info) and it essentially allows Go to safely muck around with arrays because you never grow an existing array (the size of an array is fixed at initialization). So you can never append to an array.

    What Go does to give you the illusion of appending to an array is having a larger than required underlying array, and the Slice controls the access to that array. So if the underlying array has a capacity of 5 and you already stored 3 items in it you can do 2 append operations without having to allocate a new array and copy the existing array elements to the new memory location.

    So when you are passing a []int you are actually passing an array pointer (by value) around.

    This leads to the next gotcha in your code: The use of append. As mentioned above, append takes a Slice, looks at the underlying array and how much space is actually left and then adds to it or allocates a new array. If a new array is allocated append returns a new slice that points to the new array.

    So calling:

    foo := []{1,2,3}
    append(foo, 4)
    append(foo, 5)
    append(foo, 6)
    fmt.Print(foo) 
    // => might return 1,2,3,4,5
    

    You always have to take the return value of append otherwise you risk still referencing the "old" slice that didn't get the new items appended.

    So the correct way to grow a Slice, or work with Slices in general is to keep in mind that: Slices are passed by value, so always keep updating your variables with the return values of Slice modifying functions.

    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)