This is a creation in Article, where the information may have evolved or changed.
Slice and Array dimensions are one-dimensional
Level: Beginner Entry level
Go seems to support multidimensional arrays and Slice, but it's not. Although you can create an array of array, you can also create a Slice Slice. For computationally intensive programs that rely on multidimensional arrays, Go is not the best choice, either in terms of performance or complexity.
Of course, if you choose to create nested arrays with nested Slice, then you have to be responsible for indexing, checking the following table, and allocating memory when the array grows. Nested Slice are divided into two types, Slice are nested in separate Slice, or Slice of shared data nested in Slice.
Creating a multidimensional Array with nested standalone Slice takes two steps. The first step is to create the perimeter Slice and then assign each internal Slice. The internal Slice are independent and can be scaled for each individual internal Slice.
package mainfunc main() { x := 2 y := 4 table := make([][]int,x) for i:= range table { table[i] = make([]int,y) }}
Creating a multidimensional Array with nested, shared data Slice takes three steps. First, create the data "container", the second part, create the perimeter Slice, and the third part, initialize the internal Slice.
package mainimport "fmt"func main() { h, w := 2, 4 raw := make([]int,h*w) for i := range raw { raw[i] = i } fmt.Println(raw,&raw[4]) //prints: [0 1 2 3 4 5 6 7] <ptr_addr_x> table := make([][]int,h) for i:= range table { table[i] = raw[i*w:i*w + w] } fmt.Println(table,&table[1][0]) //prints: [[0 1 2 3] [4 5 6 7]] <ptr_addr_x>}
The Go language also has proposals for supporting multidimensional arrays and Slice, but don't expect too much. The Go language authorities place these requirements in the "low priority" group.
Attempting to access a nonexistent Map key value
Level: Beginner Entry level
It is not possible in all cases to determine whether the record value of a map is nil or not. In the Go language, data types that are nil for "0 value" can be judged this way, but other data types are not available. In short, this is not a reliable practice (for example, the Boolean variable "0 value" is false). The most reliable approach is to check the second return value of the map record.
Error code:
package mainimport "fmt"func main() { x := map[string]string{"one":"a","two":"","three":"c"} if v := x["two"]; v == "" { //incorrect fmt.Println("no entry") }}
Fix code:
package mainimport "fmt"func main() { x := map[string]string{"one":"a","two":"","three":"c"} if _,ok := x["two"]; !ok { fmt.Println("no entry") }}
String is not variable
Level: Beginner Entry level
The operation of a single character in a String causes compilation to fail. The String is a read-only byte slice (byte Slices) with some additional properties. So if you want to manipulate a string, you should use a byte-slice operation instead of converting it to a string type.
Error message:
package mainimport "fmt"func main() { x := "text" x[0] = 'T' fmt.Println(x)}
Error message:
/tmp/sandbox305565531/main.go:7: cannot assign to x[0]
Fix code:
package mainimport "fmt"func main() { x := "text" xbytes := []byte(x) xbytes[0] = 'T' fmt.Println(string(xbytes)) //prints Text}
Note that the operation here is not the most correct operation, because some characters may be stored in multiple bytes. If this is the case with your development scenario, you need to convert the String to rune format first. Even Rune, a character may be saved in more than one rune, so Go string also behaves as a byte sequence (String sequences). Rune generally understood as "character", "one character may also be saved in more than one Rune" situation we will refer to below.
Conversion of String to Byte Slice
Level: Beginner Entry level
When you convert a String type and a Byte Slice type to each other, the new data is copied from the original data, not the original data. Type conversion and slice reorganization (resliciing) are different, the variable after the slice reorganization still points to the original variable, and the type-converted variable points to the copy of the original variable.
The go language has been optimized for []byte and String type conversions, and will continue to be optimized.
The first optimization avoids extra allocations when []byte keys is used to lookup entries in map[string] collections:m[ String (key)].
An optimization is
The second optimization avoids extra allocations in for range clauses where strings is converted to []byte:for i,v: = RA nge []byte (str) {...}.
String and subscript
Level: Beginner Entry level
Unlike other languages, the following table of String returns a value of type Byte instead of a character type.
package mainimport "fmt"func main() { x := "text" fmt.Println(x[0]) //print 116 fmt.Printf("%T",x[0]) //prints uint8}
If you need to remove the specified character in a String of type UTF8, you need to use the Unicode/utf8 and experimental utf8string package. The Utf8string package contains the at () method, you can remove the characters, or you can convert a String to Rune SLice.
String is not necessarily UTF8 format
Level: Beginner Entry level
The string type is not necessarily a UTF8 format, and a string can contain custom text/bytes. You need to use the UTF8 format only if you need to display the string, and in other cases you can use escape to represent any character.
You can use the Validstring () method of the weight in the Unicode/utf8 package to determine if the text is of type UTF8.
package mainimport ( "fmt" "unicode/utf8")func main() { data1 := "ABC" fmt.Println(utf8.ValidString(data1)) //prints: true data2 := "A\xfeC" fmt.Println(utf8.ValidString(data2)) //prints: false}
String length
Level: Beginner Entry level
Python Developer's Code:
data = u'' print(len(data)) #prints: 1
Convert to a similar Go code as follows:
package mainimport "fmt"func main() { data := "" fmt.Println(len(data)) //prints: 3}
The Len () method of Go is not the same as Python, and the Go method equivalent to the Python Len method is runecountinstring.
package mainimport ( "fmt" "unicode/utf8")func main() { data := "" fmt.Println(utf8.RuneCountInString(data)) //prints: 1}
Of course there are cases (such as French) where runecountinstring does not fully return the number of characters because some characters are stored in a way that uses multiple characters.
package mainimport ( "fmt" "unicode/utf8")func main() { data := "é" fmt.Println(len(data)) //prints: 3 fmt.Println(utf8.RuneCountInString(data)) //prints: 2}
Multiple rows of Slice Arry and Map assignments are missing commas
Missing Comma in multi-line Slice, Array, and Map literals
Level: Beginner Entry level
Error message:
package mainfunc main() { x := []int{ 1, 2 //error } _ = x}
Compile Errors:
/tmp/sandbox367520156/main.go:6: syntax error: need trailing comma before newline in composite literal /tmp/sandbox367520156/main.go:8: non-declaration statement outside function body /tmp/sandbox367520156/main.go:9: syntax error: unexpected }
Fix code:
package mainfunc main() { x := []int{ 1, 2, } x = x y := []int{3,4,} //no error y = y}
Of course, if you write these things in a row, you can add the last comma.
Log. Fatal and log. Panic quietly did something in the background.
Level: Beginner Entry level
The log library provides different levels of logging, and if you use Fatal and Panic-level logs, the application exits without continuing execution after the log is logged.
package mainimport "log"func main() { log.Fatalln("Fatal Level: log entry") //app exits here log.Println("Normal Level: log entry")}
Built-in data structure operation is lock-free
Level: Beginner Entry level
Although the go language is inherently high concurrency, go does not take into account data security. To achieve "atomized" data manipulation, developers need to lock up data operations themselves. Of course, goroutine and channel and sync are all good options for manual locking.