#I need help with adding output to an array
48 messages · Page 1 of 1 (latest)
the problem is, i dont want to add i to my array, i want the output of the strings.split
this is what i get now
for _, value := strings.Split(whatever) {
total_buildings = append(total_buildings, value)
}```
I forgot that there is an iterator value there that is preferred when you do the one var version of range.
I dont think i can do it
Do what?
I'm not really clear on what the file contains, and what you want out of it.
Maybe give examples of those?
GebouwA=100=GebouwB=150=GebouwC=80
GebouwD=1000
this is what the file contains
so what the for scanner.scan loop does, it reads the first line of code and stores it in ..., then it checks the second line of code but when i want to add that to the array
it overwrites
What do you want that array to contain in the end?
GebouwA,100,GebouwB,150,GebouwC,80,GebouwD,1000
but what it gives me is GebouwD,1000
Right-right. If you get stuck, let me know.
Nice!
but
is there not a way to simplify this:
for scanner.Scan() {
var tijdelijk []string = strings.Split(scanner.Text(), "=")
for i := range tijdelijk {
total_buildings = append(total_buildings, tijdelijk[i])
}
}
There is.
i tried putting the strings,split in range but didnt know how to append the output
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fragments := strings.Split(scanner.Text(), "=")
total_buildings = append(total_buildings, fragments...) // The ... means it unpacks the slice into arguments given to append
}
i still dont understand the ...
The first argument to append is the original slice, right?
yeah
The following millions and millions of arguments will get appended to that slice, and the result returned.
So the fragments... tells Go you don't want to append the slice as a slice, but as separate arguments to append.
Yes. This "trick" works for any function that takes a variable number of arguments, like append does.
i see, thanks alot man!
Sure thing.
i really appreciate it ❤️