2

I have this code, which is giving me errors:

package main

import (
    "fmt"
)

func main() {
        var cnt = make([][]string,0,10)
        for i := 0; i < 5; i++ {
             var tmp = make([]string,0,8)
             for c := 0 ; c < 5 ; c++ {
                 tmp = append(tmp,"Matias")
              }
              cnt= append(cnt,tmp...)
         }
    fmt.Println(cnt)
}

It's giving me an error. Basically what I need is to have the slice to be as dinámic as possible. I don't know what the final length will be in any of the two dimensions.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Matias Barrios
  • 4,674
  • 3
  • 22
  • 49
  • 2
    See possible duplicate: [What is a concise way to create a 2D slice in Go?](https://stackoverflow.com/questions/39804861/what-is-a-concise-way-to-create-a-2d-slice-in-go/39806983#39806983) – icza Mar 13 '19 at 16:02
  • 1
    @icza thanks for your answer. But in that case the slice is not dinámic. It's fixed to "dx" value. – Matias Barrios Mar 13 '19 at 16:11
  • `dx` is a variable, not a constant. Isn't that "dynamic"? Whatever value `dx` holds, that will be the row length ("horizontal" size). Your example in the question seems a lot more "static" with `5` and `10`. – icza Mar 13 '19 at 16:13
  • @icza yes. But it's being set somehwere. I don't want a variable determining that value other than the flow of the code. As in my case. And in the right answer which was given. Thanks anyway!! – Matias Barrios Mar 13 '19 at 16:14

1 Answers1

3

The compiler error is actually misleading - it should quote you are using tmp... which is of a variadic of strings - instead it quotes tmp which is of the correct type []string which one could use to append to cnt:

main.go:14:15:cannot use tmp (type []string) as type [][]string in append

Anyway, using tmp..., go is turning tmp from a []string into individual string parameters. Effectively:

cnt = append(cnt, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4])

And go can't append string to a [][]string type.

Change the line to:

cnt = append(cnt, tmp)
colm.anseo
  • 19,337
  • 4
  • 43
  • 52
  • Thanks so much. This is exactly what I needed. What a dumb mistake. – Matias Barrios Mar 13 '19 at 16:10
  • actually relooking at the error - it's non-obvious. `go` says `tmp` is of type `[]string` which is the _correct_ type to append with. I think the error should expand that you at using `tmp...` - which reduces it to a variadic. – colm.anseo Mar 13 '19 at 16:15