#I need help with adding output to an array

48 messages · Page 1 of 1 (latest)

zinc elm
#

You want to append to total_buildings, but you are redefining total_buildings in your strings.Split call.
Store the result of strings.Split into something else (or call it directly in the range), and total_buildings = append(total_buildings, i) in that range loop.

next lintel
#

this is what i get now

zinc elm
# next lintel
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.

next lintel
#

I dont think i can do it

zinc elm
#

Do what?

next lintel
#

What i intended to do

#

im getting confused

zinc elm
#

I'm not really clear on what the file contains, and what you want out of it.

#

Maybe give examples of those?

next lintel
#

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

zinc elm
#

What do you want that array to contain in the end?

next lintel
#

GebouwA,100,GebouwB,150,GebouwC,80,GebouwD,1000

#

but what it gives me is GebouwD,1000

zinc elm
#

That's why. You're redefining the whole array.

next lintel
#

oh

#

But i dont know how to do it instead

#

oh wait

#

ill try it

zinc elm
#

Right-right. If you get stuck, let me know.

next lintel
#

i did it!

zinc elm
#

Nice!

next lintel
#

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])

        }

    }
zinc elm
#

There is.

next lintel
#

i tried putting the strings,split in range but didnt know how to append the output

zinc elm
#
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
}
next lintel
#

i still dont understand the ...

zinc elm
#

The first argument to append is the original slice, right?

next lintel
#

yeah

zinc elm
#

The following millions and millions of arguments will get appended to that slice, and the result returned.

next lintel
#

ooh so all the contains of that fragment will be added

#

if im correct

zinc elm
#

So the fragments... tells Go you don't want to append the slice as a slice, but as separate arguments to append.

next lintel
#

yeah so all in segments

#

as*

zinc elm
#

Yes. This "trick" works for any function that takes a variable number of arguments, like append does.

next lintel
#

i see, thanks alot man!

zinc elm
#

Sure thing.

next lintel
#

i really appreciate it ❤️