array
→ inmutables.
slice
→ mutables.
Bloque de valor que se le indica la cantidad de valores que va a tener. No se puede agregar o quitar valores pero si modificar valores.
package main
import "fmt"
func main(){
var array [4]int
array[0] = 1
array[1] = 2
fmt.Println(array)
}
[1 2 0 0]
len
→ cuántos objetos tiene el array.
cap
→ capacidad de objetos que puede tener el array.
package main
import "fmt"
func main(){
var array [4]int
array[0] = 1
array[1] = 2
fmt.Println(array, len(array), cap(array))
}
[1 2 0 0] 4 4
A diferencia de los arrays
, no se le indica las cantidad de valores que va a tener.
package main
import "fmt"
func main(){
slice := []int{0, 1, 2, 3, 4, 5, 6}
fmt.Println(slice, len(slice), cap(slice))
}
[0 1 2 3 4 5 6] 7 7
package main
import "fmt"
func main(){
slice := []int{0, 1, 2, 3, 4, 5, 6}
fmt.Println(slice, len(slice), cap(slice))
fmt.Println(slice[0])
fmt.Println(slice[:3])
fmt.Println(slice[2:4])
fmt.Println(slice[4:])
}
[0 1 2 3 4 5 6] 7 7
0
[0 1 2]
[2 3]
[4 5 6]
package main
import "fmt"
func main(){
slice := []int{0, 1, 2, 3, 4, 5, 6}
fmt.Println(slice)
slice = append(slice, 7)
fmt.Println(slice)
}
[0 1 2 3 4 5 6]
[0 1 2 3 4 5 6 7]