x := [...]string{"1"}
x is an array, not a slice.
The square brackets [...] followed by the element type (string) and the list of initializers ({"1"}) define an array literal in Go. The three dots ... indicate that the length of the array should be inferred from the number of elements in the initializer list. In this case, since there is one element "1", x is an array of string with length 1.
Arrays in Go are fixed-size sequences with a predetermined number of elements, all of the same type. Once created, their size cannot be changed. They are allocated on the stack (if their size is small enough) or on the heap, depending on the context.
On the other hand, slices are dynamic, growable sequences that represent a contiguous portion of an underlying array. Slices are defined using the slice literal notation []T{...} or created from an existing array or slice using the make function or the slice expression array[low:high]. Slices hold a reference to the underlying array, a length, and a capacity.
In summary, the variable x in the provided code is an array of string with a single element "1" and a fixed length of 1.
The type of an arrary is not tied to data type of its but also has a direct relationship with the length of the array itslef(i.e. The type and The length determine jointly the type of array)
package main
import (
"fmt"
)
func main() {
str1 := []string{"a", "b", "c"}
str2 := str1[1:]
str2[1] = "new"
fmt.Println(str1) // a b new
str2 = append(str2, "z", "x", "y")
fmt.Println(str1) // a b new
}
the code under block has some typo.
数组只能与相同纬度长度以及类型的其他数组比较,切片之间不能直接比较。。
package main
import (
"fmt"
)
func main() {
fmt.Println([...]string{"1"} == [...]string{"1"})
fmt.Println([]string{"1"} == []string{"1"})
}