Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between [0] and [:1] in Go?

I split a string by spaces:

splstr = strings.Split(str, " ")

Then I iterate each word, and look at the first character like this:

splstr[i][0] == "#"

But I got these errors from that line:

... : cannot convert "#" to type uint8

... : invalid operation: splstr[i][0] == "#" (mismatched types uint8 and string)

But then I spliced it:

splstr[i][:1] == "#"

And that works. I get why [:1] is of type string, but why is [0] of type uint8? (I'm using Go 1.1.)

like image 722
Matt Avatar asked Jun 05 '13 17:06

Matt


People also ask

What is the difference between * and & In Golang?

Basic syntaxAmpersand (&) is used for obtaining the pointer of a variable while asterisks for dereferencing a pointer and defining type of a variable. We defined the language variable as a string and assigned it "golang" value.

What does <- mean in Golang?

"=" is assignment,just like other language. <- is a operator only work with channel,it means put or get a message from a channel. channel is an important concept in go,especially in concurrent programming.

What does & symbol mean in Go?

Go uses pointers like C or C++. The * symbol is used to declare a pointer and to dereference. The & symbol points to the address of the stored value.

What is type keyword in Go?

The type keyword is there to create a new type. This is called type definition. The new type (in your case, Vertex) will have the same structure as the underlying type (the struct with X and Y). That line is basically saying "create a type called Vertex based on a struct of X int and Y int".


2 Answers

Because the array notation on a string gives access to the string's bytes, as documented in the language spec:

http://golang.org/ref/spec#String_types

A string's bytes can be accessed by integer indices 0 through len(s)-1.

(byte is an alias for uint8)

like image 156
mna Avatar answered Oct 08 '22 14:10

mna


[x:x] ([:x] is a form of [0:x]) will cut a slice into another slice while [x] will retrieve the object at index x. The difference is shown below:

arr := "#####"
fmt.Println(arr[:1]) // will print out a string
fmt.Println(arr[0]) // will print out a byte

If the string is converted into []byte:

arr := []byte("#####")
fmt.Println(arr[:1]) // will print out a slice of bytes
fmt.Println(arr[0]) // will print out a byte

You can try this yourself at http://play.golang.org/p/OOZQqXTaYK

like image 21
wei2912 Avatar answered Oct 08 '22 13:10

wei2912