Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

K-Sato
K-Sato

Posted on

     

My Journey of Go (Arrays, Slices)

Arrays

In Go, anarray is a numbered sequence of elements of a single type with a fixed length(You can not resizearrays in Go). There are several ways to declare anarray in Go. Here are some examples.

varname[num]Typevarname[num]Type=[num]Type{ele1,ele2,elen....}varname=[...]Type{ele1,ele2,elen...}//name: The name of the array.//num: The number of elements that array can contain.//Type: The type of elements that the array contains.
Enter fullscreen modeExit fullscreen mode

In the following code, I'll demonstrate how to declare anarr which is composed of 3 strings in the three ways that I presented above.

① var name[num]Type

packagemainimport"fmt"funcmain(){vararr[3]stringarr[0]="Go"arr[1]="Ruby"arr[2]="Javascript"fmt.Println(arr)//=> [Go Ruby Javascript]}
Enter fullscreen modeExit fullscreen mode

② var name[num]Type = [num]Type { ele1, ele2, elen.... }

packagemainimport"fmt"funcmain(){vararr[3]string=[3]string{"Go","Ruby","Javascript"}fmt.Println(arr)//=> [Go Ruby Javascript]}
Enter fullscreen modeExit fullscreen mode

③ var name = [...] Type { ele1, ele2, elen... }

packagemainimport"fmt"funcmain(){arr3:=[...]string{"Go","Ruby","Javascript"}fmt.Println(arr3)//=> [Go Ruby Javascript]}
Enter fullscreen modeExit fullscreen mode

Slices

In Go, Aslice is a segment of an array.Slices build onarrays and provide more power, flexibility, and convenience compared toarrays. Just likearrays,Slices are indexable and have a length. But unlikearrays, they can be resized.

Declaring a Slice

ASlice can be declared in the following ways. Unlike declaring anarray, you don't have to specify the number of elements theslice can contain.

varname[]Typevarname[]Type=[]Type{ele1,ele2,elen....}name:=Array[start:end]name:=make([]Type,len,cap)//name: The name of the array.//Type: The type of elements that the array contains.//Array: An array.//make: The built-in make function.
Enter fullscreen modeExit fullscreen mode

In the following code, I'll demonstrate how to declare aslice using the four different ways of defining aslice I presented above.

① var name[]Type

packagemainimport"fmt"funcmain(){varslice1[]stringvarslice2=[]int{1,2,3}fmt.Println(slice1)//=> []fmt.Println(slice2)//=> [1 2 3]}
Enter fullscreen modeExit fullscreen mode

② var name[]Type = []Type { ele1, ele2, elen.... }

packagemainimport"fmt"funcmain(){varslice2[]string=[]string{"Go","Ruby"}fmt.Println(slice2)//=> [Go Ruby]}
Enter fullscreen modeExit fullscreen mode

③ name := Array[start:end]

As I stated above, Aslice is a segment of anarray. That means we can create a slice from an array. The table below explains how to control the elements aslice which is created from an array calledArray.

操作意味
Array[low:high]Fromlow tohigh - 1.
Array[low:]Fromlow to the last element.
Array[:high]From the first elemet tohigh - 1.
Array[:]From the first element to the last element.
packagemainimport"fmt"funcmain(){arry:=[6]int{1,2,3,4,5,6}slice3:=arry[0:2]slice4:=arry[0:]slice5:=arry[:4]slice6:=arry[:]fmt.Println(slice3)//=> [1 2]fmt.Println(slice4)//=> [1 2 3 4 5 6]fmt.Println(slice5)//=> [1 2 3 4]fmt.Println(slice6)//=> [1 2 3 4 5 6]}
Enter fullscreen modeExit fullscreen mode

④ name := make( []Type, len, cap)

packagemainimport"fmt"funcmain(){slice7:=make([]string,2,2)fmt.Println(slice7)//=> [ ]}
Enter fullscreen modeExit fullscreen mode

Modifying a slice

As I mentioned several times, aslice is a segment of anarray and it refers to an underlying array. Therefore, modifying the elements of aslice will also modify the corresponding elements in the referenced array.

packagemainimport"fmt"funcmain(){arry:=[...]string{"Go","Ruby","Javascript"}slice:=arry[:]fmt.Println(slice)//=> [Go Ruby Javacript]slice[0]="Python"fmt.Println(slice)//=> [Python Ruby Javascript]fmt.Println(arry)//=> [Python Ruby Javascript]}
Enter fullscreen modeExit fullscreen mode

Length and Capacity of a Slice

Aslice has both alength and acapacity.

  • The length of a slice is the number of elements it contains.
  • The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.

You can find the length and capacity of a slice using the built-in functionslen() andcap().

packagemainimport"fmt"funcmain(){arry:=[...]string{"Go","Ruby","Javascript"}slice:=arry[:1]fmt.Println(len(slice),cap(slice))//=> 1 3}
Enter fullscreen modeExit fullscreen mode

Appending to a slice

It is common to append new elements to a slice, and so Go provides a built-inappend function. It takes a slice and new elements that you want to append to theslice. It then returns a new slice containing all the elements from the given slice as well as the new elements.

The following code shows the structure ofappend function.

funcappend(slice[]Type,new_elements)[]Type//Type: The type of elements that the array contains.
Enter fullscreen modeExit fullscreen mode
packagemainimport"fmt"funcmain(){arry:=[...]string{"Go","Ruby","Javascript"}slice:=arry[:]varnew_slice=append(slice,"Java","Swift","C")fmt.Println(new_slice)//=> [[Go Ruby Javascript Java Swift C]}
Enter fullscreen modeExit fullscreen mode

Nil slices

The zero value of a slice isnil. Anil slice has alength andcapacity of 0 and has no underlying array.

packagemainimport"fmt"funcmain(){varnil_slice[]intifnil_slice==nil{fmt.Println("nil")//=> nil}
Enter fullscreen modeExit fullscreen mode

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
kashlinda3 profile image
Kash Linda
  • Joined

Great, I have found great knowledge through your writing. I will take a closer look and introduce some useful information in your article. Thanks very much.venge io

CollapseExpand
 
agario profile image
agario unblocked
  • Joined

New agario The ATRIP remix for ‘Monchou’ by IMANU is chill, great agario game
agario

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer
  • Work
    Software Engineer
  • Joined

More fromK-Sato

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp