English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básico do Golang

Sentença de controle do Golang

Função & Método do Golang

Estrutura do Golang

Slice & Array do Golang

String (String) do Golang

Ponteiro do Golang

Interface do Golang

Concorrência do Golang

Exceções (Error) do Golang

Outros itens de Golang

Fatia (Slice) do Linguagem Go

No idioma Go, a slice é maisArrayMais poderoso, flexível, conveniente e leve. A slice é uma sequência de comprimento variável, usada para armazenar elementos do mesmo tipo, não permitindo que diferentes tipos de elementos sejam armazenados na mesma slice. Assim como um array com índice e comprimento, mas o tamanho da slice pode ser ajustado, e a slice não está em tamanho fixo como o array. Internamente, a slice e o array estão conectados, e a slice é uma referência ao array básico. Permite que elementos repetidos sejam armazenados na slice.A primeira posição de índice na fatia sempre é 0, enquanto a última posição de índice será (o comprimento da fatia - 1) 1).

Declaração de fatia

A declaração de fatia é semelhante à de array, mas não inclui o tamanho da fatia. Portanto, ela pode crescer ou encolher conforme necessário.

Sintaxe:

[]T
ou
[]T{}
ou
[]T{value1, value2, value3, ...value n}

Aqui, T é o tipo do elemento. Por exemplo:

var my_slice[]int

Componentes da fatia

A fatia contém três componentes:

  • Ponteiro:O ponteiro é usado para apontar para o primeiro elemento do array que pode ser acessado via fatia. Aqui, o elemento apontado não precisa ser o primeiro elemento do array.

  • Largura:A largura é o número total de elementos existentes no array.

  • Capacidade:A capacidade representa o tamanho máximo que pode ser expandido.

Vamos discutir todos esses componentes com exemplos:

//Fatia
package main
import "fmt"
func main() {
    //Create an array
    arr := [7]string{"Este", "é", "Golang", "básico", "tutorial", "online", "pt.oldtoolbag.com"
    //Exibir o array
    fmt.Println("Array:", arr)
    //Criação de fatias
    myslice := arr[1:6]
    //Exibir a fatia
    fmt.Println("Fatia:", myslice)
    //Exibir a largura da fatia
    fmt.Printf("Largura da fatia: %d", len(myslice))
    //Exibir a capacidade da fatia
    fmt.Printf("\nCapacidade da fatia: %d", cap(myslice))
}

Saída:

Array: [Este é o tutorial básico do Golang online pt.oldtoolbag.com]
Fatia: [É o tutorial básico do Golang online]
Largura da fatia: 5
Capacidade da fatia: 6

Explicação de uso:No exemplo acima, criamos uma fatia a partir do array fornecido. Aqui, o ponteiro da fatia aponta para o índice1porque o limite inferior da fatia é definido como1então começa a acessar os elementos a partir do índice1A largura da fatia é5representa o número total de elementos na fatia5enquanto a fatia6A capacidade representa o número máximo de elementos que podem ser armazenados6elementos.

Como criar e inicializar fatias?

No Go, você pode criar e inicializar fatias da seguinte forma:

  • Usar literals de fatias:Você podeUso de literals de fatiasCriar fatias. A criação de literals de fatias é semelhante à de literals de arrays, mas há uma diferença, pois não é permitido especificar o tamanho da fatia dentro dos colchetes []. Assim, como exemplo, o lado direito da expressão é um literal de fatia.

    var my_slice_1 = []string "{w3codeboxs "for", "w3codeboxs ""

    Atenção:Remember, when you create a slice using string literals, it first creates an array and then returns a slice reference to it.

    // Create a slice literal using a slice
    package main
    import "fmt"
    func main() {
        //Create a slice using the var keyword
        var my_slice_1 = []string "{w3codeboxs "for", "w3codeboxs ""
        fmt.Println("My Slice 1:", my_slice_1)
        //Criação de fatias
        //Using a shorthand declaration
        my_slice_2 := []int{12, 45, 67, 56, 43, 34, 45}
        fmt.Println("My Slice 2:", my_slice_2)
    }

    Saída:

    My Slice 1: [w3codeboxs for w3codeboxs]
    My Slice 2: [12 45 67 56 43 34 45]
  • Using an array:We already knowSlices are references to arraysTherefore, you can create a slice from the given array. To create a slice from the given array, you first need to specify the lower and upper limits, which means the slice can start getting elements from the lower limit to the upper limit in the array. It does not include the element starting from the upper limit. As shown in the following example:

    Sintaxe:

    array_name[low:high]

    This syntax returns a new slice.

    Atenção:The default lower limit is 0, and the default upper limit is the total number of elements present in the given array.

  • //Create a slice from an array
    package main 
      
    import "fmt"
      
    func main() { 
      
        //Create an array
        arr := [4]string "{w3codeboxs "for", "w3codeboxs "GFG" 
      
        //Create a slice from a given array 
        var my_slice_1 = arr[1:2] 
        my_slice_2 := arr[0: 
        my_slice_3 := arr[:2] 
        my_slice_4 := arr[: 
      
        //Show result
        fmt.Println("My array: ", arr) 
        fmt.Println("My Slice 1: "my_slice_1) 
        fmt.Println("My Slice 2: "my_slice_2) 
        fmt.Println("My Slice 3: "my_slice_3) 
        fmt.Println("My Slice 4: "my_slice_4) 
    }

    Saída:

    My array: [w3codeboxs for w3codeboxs GFG]
    My Slice 1: [for]
    My Slice 2: [w3codeboxs for w3codeboxs GFG]
    My Slice 3: [w3codeboxs for]
    My Slice 4: [w3codeboxs for w3codeboxs GFG]
  • Using an existing slice:You can also create a slice from the given slice. To create a slice from the given slice, you first need to specify the lower and upper limits, which means the slice can start getting elements from the lower limit to the upper limit in the given slice. It does not include the element starting from the upper limit. As shown in the following example:

    Sintaxe:

    slice_name[low:high]

    This syntax returns a new slice.

    Atenção:The default lower limit is 0, and the default upper limit is the total number of elements present in the given slice.

    //Create a slice from an array
    package main
    import "fmt"
    func main() {
        //Criação de fatias
        oRignAl_slice := []int{90, 60, 40, 50, 34, 49, 30}
        //Create a slice from the given slice
        var my_slice_1 = oRignAl_slice[1:5]
        my_slice_2 := oRignAl_slice[0:
        my_slice_3 := oRignAl_slice[:6]
        my_slice_4 := oRignAl_slice[:
        my_slice_5 := my_slice_3[2:4]
        //Show result
        fmt.Println("Original slice:", oRignAl_slice)
        fmt.Println("Novo slice" 1:", my_slice_1)
        fmt.Println("Novo slice" 2:", my_slice_2)
        fmt.Println("Novo slice" 3:", my_slice_3)
        fmt.Println("Novo slice" 4:", my_slice_4)
        fmt.Println("Novo slice" 5:", my_slice_5)
    }

    Saída:

    Slice original: [90 60 40 50 34 49 30]
    Novo slice 1: [60 40 50 34]
    Novo slice 2: [90 60 40 50 34 49 30]
    Novo slice 3: [90 60 40 50 34 49]
    Novo slice 4: [90 60 40 50 34 49 30]
    Novo slice 5: [40 50]
  • Uso da função make():Você também pode usar as bibliotecas fornecidas pelo gofunção make()Cria um slice. Esta função aceita três parâmetros, ou seja, tipo, comprimento e capacidade. Aqui, o valor da capacidade é opcional. O tamanho alocado para o array subjacente é igual ao valor da capacidade e retorna um slice que referencia o array subjacente. Normalmente, a função make() é usada para criar um slice vazio. Aqui, o slice vazio é aquele que contém referências de array vazio.

    Sintaxe:

    func make([]T, len, cap) []T
    //Uso da função make
    package main
    import "fmt"
    func main() {
        //Cria um slice de tamanho7do array
        //Corta este array em4
        //e retorna uma referência do slice
        //Uso da função make
        var my_slice_1 = make([]int, 4, 7)
        fmt.Printf("Slice 1 = %v, 
     tamanho = %d, 
    capacidade = %d
    1, len(my_slice_1), cap(my_slice_1))
        //Cria outro array de tamanho7do array
        //e retorna uma referência do slice
        //Uso da função make
        var my_slice_2 = make([]int, 7)
        fmt.Printf("Slice 2 = %v, 
     tamanho = %d, 
    capacidade = %d
    2, len(my_slice_2), cap(my_slice_2))
    }

    Saída:

    Fatia 1 = [0 0 0 0], 
    tamanho = 4, 
    capacidade = 7
    Fatia 2 = [0 0 0 0 0 0 0], 
    tamanho = 7, 
    capacidade = 7

Como percorrer um slice?

Você pode percorrer o slice da seguinte forma:

  • Uso do laço for:Esta é a maneira mais simples de iterar sobre um slice, como mostrado nos exemplos a seguir:

    // Iteração no laço for
    package main 
      
    import "fmt"
      
    func main() { 
      
        //Criação de fatias
        myslice := []string{"This", "is", "the", "tutorial", "of", "Go", "language"} 
      
        //Iteração com laço for
        for e := 0; e < len(myslice); e++ { 
            fmt.Println(myslice[e]) 
        } 
    }

    Saída:

    Este
    é
    o
    tutorial
    de
    Go
    language
  • Uso do range no laço for:Permite usar o range no laço for para iterar sobre o slice. No laço for com range, você pode obter o índice e o valor do elemento, como mostrado no exemplo:

    //Uso do slice no laço for
    package main 
      
    import "fmt"
      
    func main() { 
      
        //Criação de fatias
        myslice := []string{"This", "is", "the", "tutorial", "of", "Go", "language"} 
      
            //迭代切片
            //在for循环中使用range
        for index, ele := range myslice { 
            fmt.Printf("Índice = %d e element = %s\n", index+3, ele) 
        } 
    }

    Saída:

    Índice = 3 element = Este
    Índice = 4 element = é
    Índice = 5 element = o
    Índice = 6 element = tutorial
    Índice = 7 element = de
    Índice = 8 element = Go
    Índice = 9 element = language
  • 在for循环中使用空白标识符:在for循环范围内,如果您不想获取元素的索引值,则可以使用空格(_)代替索引变量,如以下示例所示:

    //在for循环中使用范围的切片而没有索引 
    package main 
      
    import "fmt"
      
    func main() { 
      
        //Criação de fatias 
        myslice := []string{"This", "is", "the", "tutorial", "of", "Go", "language"} 
      
            //迭代切片
            //在for循环中使用range
            //没有索引
        for _, ele := range myslice { 
            fmt.Printf("Element = %s\n", ele) 
        } 
    }

    Saída:

    Element = This
    Element = is
    Element = the
    Element = tutorial
    Element = of
    Element = Go
    Element = language

关于切片的要点

  1. 零值切片:在Go语言中,允许您创建一个不包含任何元素的零切片。因此,此片的容量和长度为0。nil切片不包含数组引用,如以下示例所示:

    package main 
      
    import "fmt"
      
    func main() { 
      
        // 创建零值切片
        var myslice []string 
        fmt.Printf("Length = %d\n", len(myslice)) 
        fmt.Printf("Capacity = %d ", cap(myslice)) 
      
    }

    Saída:

    Length = 0
    Capacity = 0
  2. 修改Slice:正如我们已经知道slice是引用类型一样,它可以引用基础数组。因此,如果我们更改切片中的某些元素,则更改也应发生在引用数组中。换句话说,如果您对切片进行了任何更改,则切片也会反映在数组中,如以下示例所示:

    //如何修改切片
    package main 
      
    import "fmt"
      
    func main() { 
      
        //创建零值切片
        arr := [6]int{55, 66, 77, 88, 99, 22} 
        slc := arr[0:4] 
      
        //修改前
      
        fmt.Println("Original_Array: ", arr) 
        fmt.Println("Original_Slice: ", slc) 
      
        //修改后 
        slc[0] = 100 
        slc[1] = 1000 
        slc[2] = 1000 
      
        fmt.Println("\nNew_Array: ", arr) 
        fmt.Println("New_Slice: ", slc) 
    }

    Saída:

    Original_Array:  [55 66 77 88 99 22]
    Original_Slice:  [55 66 77 88]
    New_Array:  [100 1000 1000 88 99 22]
    New_Slice:  [100 1000 1000 88]
  3. Comparação de fatias:Dentro da fatia, você pode usar==Operador de comparação verifica se a fatia existe.==Operadores de comparação de fatias:

    //Determinar se a fatia é nula
    package main 
      
    import "fmt"
      
    func main() { 
      
        //Criação de fatias
        s1 := []int{12, 34, 56} 
        var s2 []int
      
            //se você tentar executar este comentário
            //O compilador de código fornecerá um erro
        /*s3:= []int{23, 45, 66} 
          fmt.Println(s1==s3) 
        */
      
        //Verificar se a fatia fornecida é nula
        fmt.Println(s1 == nil) 
        fmt.Println(s2 == nil) 
    }

    Saída:

    false
    true

    Atenção:Se você quiser comparar duas fatias, use correspondência de intervalo de loop para cada elemento ou você pode usarDeepEqualFunções.

  4. Fatias multidimensionais:Fatias multidimensionais são semelhantes a arrays multidimensionais, mas as fatias não contêm tamanho.

    package main 
      
    import "fmt"
      
    func main() { 
      
        //Criação de fatias multidimensionais
        s1 := [][]int{{12, 34}, 
            {56, 47}, 
            {29, 40}, 
            {46, 78}, 
        } 
      
        //Acesso a fatias multidimensionais
        fmt.Println("Slice 1 : ", s1) 
      
        //Criação de fatias multidimensionais 
        s2 := [][]string{ 
            []string{"w3codeboxs", "for"}, 
            []string{"w3codeboxs", "GFG"}, 
            []string{"gfg", "w3codebox"}, 
        } 
      
        //Acesso a fatias multidimensionais
        fmt.Println("Slice 2 : ", s2) 
      
    }

    Saída:

    Fatia 1 :  [[12 34]]56 47]]29 40] [46 78]]
    Fatia 2 :  [[w3codeboxs for] [w3codeboxs GFG] [gfg w3codebox]]
  5. Ordenação de fatias:Em Go, é possível ordenar os elementos existentes em uma fatia. A biblioteca padrão do Go, sort, oferece pacotes que contêm funções para ordenar int, float64Diferentes métodos de ordenação para fatias de strings e outros tipos. Essas funções ordenam sempre as fatias disponíveis em ordem crescente.

    //Elementos existentes na fatia
    package main 
      
    import ( 
        "fmt"
        "sort"
    ) 
      
    func main() { 
      
        //Criação de fatias
        slc1 := []string{"Python", "Java", "C#", "Go", "Ruby"} 
        slc2 := []int{45, 67, 23, 90, 33, 21, 56, 78, 89} 
      
        fmt.Println("Antes da ordenação:") 
        fmt.Println("Slice 1: ", slc1) 
        fmt.Println("Slice 2: ", slc2) 
      
        //Uso de funções de ordenação de fatias
        sort.Strings(slc1) 
        sort.Ints(slc2) 
      
        fmt.Println("\nOrdenação: ") 
        fmt.Println("Slice 1: ", slc1) 
        fmt.Println("Slice 2: ", slc2) 
      
    }

    Saída:

    Antes da ordenação:
    Fatia 1:  [Python Java C# Go Ruby]
    Fatia 2:  [45 67 23 90 33 21 56 78 89]
    Ordenação:  [Python Java C# Go Ruby]
    Fatia 1:  [C# Go Java Python Ruby]
    Fatia 2:  [21 23 33 45 56 67 78 89 90]