简体   繁体   中英

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()
}

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:
ijkl

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

Try to rewrite the code from scratch.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM