Jetlum Ajeti
Jetlum Ajeti

Reputation: 21

What's the output of this golang code?

My output says

.\main1.go:8: invalid identifier character U+200b

.\main1.go:8: undefined: ​fmt in ​fmt.Print

I even tried it on go playground same response.

Someone posted an answer "0 1 2 3" with the same code.

How come I copied the same code but with the above result.

package main

import "fmt"

func main() {
x := []string{"i","j","k","l"}
for v := range x {
  ​fmt.Print(v, " ")
  }
fmt.Println()
}

Upvotes: 0

Views: 611

Answers (4)

Apoorva Manjunath
Apoorva Manjunath

Reputation: 855

The line 8 of your code has Zero Width Space character, which is a non-printable character. This could be in the source you copied from.

Re-writing the line after removing spaces as below works fine.

package main

import "fmt"

func main() {
    x := []string{"i", "j", "k", "l"}
    for v := range x {
        fmt.Print(v, " ")
    }
    fmt.Println()
}

Output:

0 1 2 3

When you run go fmt on your code, it says filename.go:8:5: illegal character U+200B, which specifies the position of ZWSP.

Upvotes: 0

user6169399
user6169399

Reputation:

there are 2 things to note:
first: if you view your source file with simple Hex Viewer, you will see some extra hex bytes before fmt.Print(v, " "):
20 20 E2 80 8B
lets delete it and now we have:

package main

import "fmt"

func main() {
    x := []string{"i", "j", "k", "l"}
    for v := range x {
        fmt.Print(v, " ")
    }
    fmt.Println()
}

now the output is:
0 1 2 3

second:
but normally we use variable names like v for value and var named i for index,
so it seems the code needs attention:

package main

import "fmt"

func main() {
    x := []string{"i", "j", "k", "l"}
    for _, v := range x {
        fmt.Print(v, " ")
    }
    fmt.Println()
}

now output is:
i j k l

Upvotes: 3

Carl Veazey
Carl Veazey

Reputation: 18363

Wherever you copied it from copied some additional characters, specifically a unicode zero-dith space, and put them in between the opening brace in the for ... range statement, and the fmt.Print(...). Looking at the paste output in a hex editor reveals this is the case. If you select and delete this character which is prior to the fmt.Print, go fmt will run again and the program will compile. Deleting all the white space before that statement works, too.

Upvotes: 2

WilQu
WilQu

Reputation: 7383

U+200b is apparently the zero-width space. It probably appeared after a weird copy-paste.

Try to rewrite the code from scratch.

Upvotes: 2

Related Questions