内容纲要

空切片

package main

import "fmt"

func main() {
    // Declare a nil slice
    var x []int
    fmt.Println(x, len(x), cap(x))
    x = append(x, 10, 20, 30)
    fmt.Println("Slice x after appending data:", x)
}
// Creating a slice using a slice literal
var s = []int{3, 5, 7, 9, 11, 13, 17}
package main
import "fmt"

func main() {
    var a = [5]string{"Alpha", "Beta", "Gamma", "Delta", "Epsilon"}

    // Creating a slice from the array
    var s []string = a[1:4]

    fmt.Println("Array a = ", a)
    fmt.Println("Slice s = ", s)
}
package main
import "fmt"

func main() {
    a := [5]string{"C", "C++", "Java", "Python", "Go"}

    slice1 := a[1:4]
    slice2 := a[:3]
    slice3 := a[2:]
    slice4 := a[:]

    fmt.Println("Array a = ", a)
    fmt.Println("slice1 = ", slice1)
    fmt.Println("slice2 = ", slice2)
    fmt.Println("slice3 = ", slice3)
    fmt.Println("slice4 = ", slice4)
}
# Output
Array a =  [C C++ Java Python Go]
slice1 =  [C++ Java Python]
slice2 =  [C C++ Java]
slice3 =  [Java Python Go]
slice4 =  [C C++ Java Python Go]

迭代

package main
import "fmt"

func main() {
    countries := []string{"India", "America", "Russia", "England"}

    for i := 0; i < len(countries); i++ {
        fmt.Println(countries[i])
    }
}
package main
import "fmt"

func main() {
    primeNumbers := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}

    for index, number := range primeNumbers {
        fmt.Printf("PrimeNumber(%d) = %d\n", index+1, number)
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注