Como acrescentar uma fatia em Golang?
Na linguagem Go, o slice é mais poderoso, flexível, conveniente do que um array e é uma estrutura de dados leve. Uma fatia é uma sequência de comprimento variável que armazena elementos de um tipo semelhante; você não tem permissão para armazenar diferentes tipos de elementos na mesma fatia. É como uma array com um valor de índice e comprimento, mas o tamanho da fatia é redimensionado; eles não têm um tamanho fixo como uma array.
Como já sabemos, essa fatia é dinâmica, então o novo elemento pode ser anexado a uma fatia com a ajuda da função append(). Esta função anexa o novo elemento no final da fatia.
Sintaxe:
func append(s []T, x ...T) []T
Aqui, esta função leva s fatia ex… T significa que esta função leva um número variável de argumentos para o parâmetro x . Esse tipo de função também é conhecido como função variada.
Se a fatia é apoiada pela array e as arrayes têm comprimento fixo, como é possível que uma fatia tenha um comprimento dinâmico?
Bem, a resposta é quando os novos elementos acrescentam à fatia, um novo array é criado. Agora, os elementos presentes na array existente são copiados em uma nova array e retornam uma nova referência de fatia a esta array (nova array). Então, devido a isso, a capacidade da fatia vai ser o dobro da capacidade antiga (conforme mostrado no exemplo 1). Mas se a fatia existente tiver capacidade suficiente para conter novos elementos, nenhum novo array será criado e os elementos serão armazenados no array subjacente existente (conforme mostrado no exemplo 2).
Exemplo 1:
// Go program to illustrate the
// concept of appending slices.
package main
import (
"fmt"
)
func main() {
// Creating and initializing slice
// Using shorthand declaration
s1 := []int{234, 567, 7890, 1234, 234}
s2 := []string{"Geeks", "For", "Geeks"}
// Displaying slices with
// their length and capacity
fmt.Println("Slice_1: ", s1)
fmt.Println("Length of Slice_1: ", len(s1))
fmt.Println("Capacity of Slice_1: ", cap(s1))
fmt.Println()
fmt.Println("Slice_2: ", s2)
fmt.Println("Length of Slice_2: ", len(s2))
fmt.Println("Capacity of Slice_2: ", cap(s2))
// Appending slices
// Using append() function
res1 := append(s1, 1000)
res2 := append(s2, "GFG")
// Displaying results
fmt.Println()
fmt.Println("New slice_1: ", res1)
fmt.Println("New length of slice_1: ", len(res1))
fmt.Println("New capacity of slice_1: ", cap(res1))
fmt.Println()
fmt.Println("New slice_2: ", res2)
fmt.Println("New length of slice_2: ", len(res2))
fmt.Println("New capacity of slice_2: ", cap(res2))
}
Saída:
Slice_1: [234 567 7890 1234 234] Length of Slice_1: 5 Capacity of Slice_1: 5 Slice_2: [Geeks For Geeks] Length of Slice_2: 3 Capacity of Slice_2: 3 New slice_1: [234 567 7890 1234 234 1000] New length of slice_1: 6 New capacity of slice_1: 12 New slice_2: [Geeks For Geeks GFG] New length of slice_2: 4 New capacity of slice_2: 6
Exemplo 2:
// Go program to illustrate the
// concept of appending slices.
package main
import "fmt"
func main() {
// Creating and initializing slice
// Using make() function
// Here 4 and 6 is the length
// and capacity of the slice
s1 := make([]int, 4, 6)
// Copying the elements in the slice
// Using copy() function
copy(s1, []int{123, 456, 789, 977})
// Displaying slice
fmt.Println("Slice : ", s1)
fmt.Println("Length: ", len(s1))
fmt.Println("Capacity: ", cap(s1))
// Appending slice
// Using append() function
s2 := append(s1, 3454, 678)
// Displaying slice
fmt.Println()
fmt.Println("Slice : ", s2)
fmt.Println("Length: ", len(s2))
fmt.Println("Capacity: ", cap(s2))
}
Saída:
Slice : [123 456 789 977] Length: 4 Capacity: 6 Slice : [123 456 789 977 3454 678] Length: 6 Capacity: 6
Anexando à fatia nula: Como sabemos que o tipo de fatia de valor zero é nulo e a capacidade e o comprimento desse tipo de fatia é 0. Mas com a ajuda da função append, é possível anexar valores à fatia nula.
Exemplo:
// Go program to illustrate the
// concept of appending to nil slice.
package main
import "fmt"
func main() {
// Creating nil slice
var s1 []int
// Displaying slice
fmt.Println("Slice : ", s1)
fmt.Println("Length: ", len(s1))
fmt.Println("Capacity: ", cap(s1))
// Appending to nil slice
// Using append() function
s2 := append(s1, 89, 45, 67, 23)
// Displaying slice
fmt.Println()
fmt.Println("Slice : ", s2)
fmt.Println("Length: ", len(s2))
fmt.Println("Capacity: ", cap(s2))
}
Saída:
Slice : [] Length: 0 Capacity: 0 Slice : [89 45 67 23] Length: 4 Capacity: 4
Anexando a outra fatia usando o operador…: Você tem permissão para anexar uma fatia a outra com a ajuda do operador … .
Exemplo:
// Go program to illustrate the concept
// of appending to another slice.
package main
import "fmt"
func main() {
// Creating and initializing slice
// Using shorthand declaration
s1 := []int{234, 567, 7890, 1234, 234}
s2 := []int{10, 100, 1000, 10000}
// Displaying slices with their
// length and capacity
fmt.Println("Slice_1: ", s1)
fmt.Println("Length of Slice_1: ", len(s1))
fmt.Println("Capacity of Slice_1: ", cap(s1))
fmt.Println()
fmt.Println("Slice_2: ", s2)
fmt.Println("Length of Slice_2: ", len(s2))
fmt.Println("Capacity of Slice_2: ", cap(s2))
// Appending to another slice
// Using append() function
res1 := append(s1, s2...)
// Displaying result
fmt.Println()
fmt.Println("New slice_1: ", res1)
fmt.Println("New length of slice_1: ", len(res1))
fmt.Println("New capacity of slice_1: ", cap(res1))
}
Saída:
Slice_1: [234 567 7890 1234 234] Length of Slice_1: 5 Capacity of Slice_1: 5 Slice_2: [10 100 1000 10000] Length of Slice_2: 4 Capacity of Slice_2: 4 New slice_1: [234 567 7890 1234 234 10 100 1000 10000] New length of slice_1: 9 New capacity of slice_1: 12
As postagens do blog Acervo Lima te ajudaram? Nos ajude a manter o blog no ar!
Faça uma doação para manter o blog funcionando.
70% das doações são no valor de R$ 5,00...
Diógenes Lima da Silva