DEV Community

loading...

Golang basic: slice

shellrean profile image ShellRean ・2 min read

Array is make you think is there any way to make size of array dynamic? and you ask to god, yeah there is a slice. Slice as same as array, a variable has more than 1 values.
Let's we write our code.

Declare Slice

Declare slice is simple, how do that?

package main

import "fmt"

func main() {
    var students []string
    // OR
    students := []string{}
}
Enter fullscreen mode Exit fullscreen mode

You don't need to include number in [] it will make a dynamic size.

Assign data to slice

How to assign data to slice? the key is same as array, look at code below.

package main

import "fmt"

func main() {
    students := []string{"Linda","Lingling","Wang"}

    fmt.Println(students)
}
Enter fullscreen mode Exit fullscreen mode

Access data slice

You can use [index] to access the value.

package main

import "fmt"

func main() {
    students := []string{"Linda","Lingling","Wang"}
    // Access single data
    fmt.Println(students[1])
}
Enter fullscreen mode Exit fullscreen mode

At the code, we get 1 as index, so if we mapped the value
0 => Linda
1 => Lingling
2 => Wang
it will return "lingling". But I want to get "lingling" and "Wang" how to do that?

package main

import "fmt"

func main() {
    students := []string{"Linda","Lingling","Wang"}

    // Access multiple data
    fmt.Println(students[1:3])
}

Enter fullscreen mode Exit fullscreen mode

you can use format slices[indexfrom:end] to access multiple data

Change single data slice

so how to change that data?

package main

import "fmt"

func main() {
    students := []string{"Linda","Lingling","Wang"}

    // Change data
    students[1] = "Longda"

    // Access data
    fmt.Println(students[1])
}
Enter fullscreen mode Exit fullscreen mode

Add data at the end of slice

So now we want to add student, we can use append in order to add.

package main

import "fmt"

func main() {
    students := []string{"Linda","Lingling","Wang"}

    students = append(students, "Boru")

    fmt.Println(students)
}
Enter fullscreen mode Exit fullscreen mode

so format of appendisappend(slice, value)`

Conclusion

We have knew about slice and how to write slice in golang, there is many ways to roman city. If you think the data is difficult to predict how size of array max, slice is the best choice for you, even the author of golang, suggest to use slice than array.

Discussion (0)

pic
Editor guide