My goal below is to return a slice of slices, so I can iterate over them later in my main function.
The current behavior is the "test" variable will show each line in a slice when I print it at fmt.PrintLn(test)
, but the "parsed" variable when printed at fmt.PrintLn(showParsed)
is empty. How can I resolve that?
func lsCommand(outString string) []string {
scanner := bufio.NewScanner(strings.NewReader(outString))
var parsed []string
for scanner.Scan() {
s := scanner.Text()
ss := strings.Fields(s)
test := append(parsed, ss...)
fmt.Println(test)
}
return parsed
}
func main() {
ctx := context.Background()
ok, outString, errString := runBashCommandAndKillIfTooSlow(ctx, "ls", 2000*time.Millisecond)
if ok != true {
panic(errString)
}
showParsed := lsCommand(outString)
fmt.Println(showParsed)
}
append
isn't guaranteed to modify the slice passed to it, so parsed
isn't changed. Only test
contains the elements of ss
. Use the returned value in each iteration:
var parsed []string
for scanner.Scan() {
s := scanner.Text()
ss := strings.Fields(s)
parsed = append(parsed, ss...)
}
return parsed