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 `[]`
}
}
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.
There are a few issues in your code:
strToInt
.employeeDataInt
in main
but it is undefined there (which should be causing a compile error, not a runtime issue).employeeDataString
twice, in two different scopes in main
(inside and outside the for
loop), with two different types ([]string
and []int
). The outer-scoped variable is unused, so should also be causing a compile error.playerData2
which is never defined or used - again, this should be causing a compiler error, not incorrect behavior.Given there were compile errors in the code, either some crucial code was missing from your post, or you did not notice/mention the compile errors.
The correct code within main would be:
var employeeDataInt []int // Seems like you just have the wrong variable name here
for _, employee := range employeeLine {
employeeDataString := strings.Split(employee, " ")
// You're missing the assignment here
employeeDataInt = strToInt(employeeDataString, employeeDataInt)
fmt.Println(employeeDataInt) // This was referencing the wrong variable
}