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.)
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.
"=" 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.
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.
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".
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)
[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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With