Dariel Pratama
Dariel Pratama

Reputation: 1675

"cannot use as type string in assignment"

I have the following string:

-1,856,32,0,0,0.000000,0.000000
0,0,0,137,0,0,0,140
0,0,101,0,0,0,42,0
0,0,0,0,0,0,0,0
0,0,0,0,0,0,554,0
-1,841,1,0,0,0.000000,0.000000
0,0,0,163,0,0,0,182
0,0,120,0,0,0,43,0
0,0,0,0,0,0,0,0
0,0,0,0,0,0,517,0

then I split it by using separator -1 which mean there will be an array consisting of 2 elements (let's call it array1). now, let say on the first element of array1 I want to split it again by \r\n, which will be an array (array2) consisting of 5 elements. next, I want to split the first element of array2 by using , as the separator, but it give me a warning saying:

cannot use strings.Split(d0, ",") (type []string) as type string in assignment

here is the code:

array1 := strings.Split(string(b), "-1,")
for k, chunk := range chunks{
    // skip the first
    // because it's blank
    // duno why
    if k == 0{
        continue
    }

    array2 := strings.Split(chunk, "\r\n")

    d0 := data[0]
    d0 = strings.Split(d0, ",") // this give me error: cannot use strings.Split(d0, ",") (type []string) as type string in assignment
    lat, lng := d0[4], d0[5]
    // 
    //  TODO: match lat and lng againts lamp table in DB which is now in $coords
    //  
    fmt.Println(lat, lng)

    data = data[1:]
    for _, v := range data{
        _ = v
    }
}

Upvotes: 4

Views: 15729

Answers (1)

maerics
maerics

Reputation: 156434

The answer to your question is in the error message you noted:

cannot use strings.Split(d0, ",") (type []string) as type string in assignment

The reason is that you declare d0 as having type "string" and then you try to assign a slice of strings to it. Since those are different types the compiler generates the error you listed and refuses to compile your program.

d0 := data[0] // Here we declare d0 as a string and assign a value to it
d0 = strings.Split(d0, ",") // ERROR: "Split" returns a []string but d0 is a string!

To work around you should simply declare a new variable that is a slice of strings instead of trying to reuse the name d0:

d0 := data[0] // Define d0 as a string
ss := strings.Split(d0, ",") // OK: Define ss as a []string

Upvotes: 4

Related Questions