Arrays and Slices for Getting Started with the Go Language

Arrays and Slices

array

Definition: A collection of elements of the same type

var a[3]int    //Defines an array whose subscripts start at 0 and whose length is n has a valid range from 0 to n-1
func arraySet() {
   var a[6] int
   a[0] = 1
   a[1] = 2
   fmt.Printf("array is %v\n",a)
   var b[3]int = [3]int{1,2,3}
   fmt.Println(b)
   c := [...]int{1,3,4}
   fmt.Println(c)
   d := [3]int{10}
   fmt.Println(d)
   e := [3]int{2:10}   // The value of subscript 2 is set to 10
   fmt.Println(e)
}

Arrays must be of the same type and length in order to be assigned equal values

Array traversal

func loopArray() {
   a := [...]int{1,2,3,4,5,6,7,8,9,10}
   for index,val := range a {
      fmt.Printf("index:%d\tvalue:%d\n",index,val)
   }
   b := [6]string{"a","b","c","d","e","f"}
   for i:=0;i<len(b);i++ {
      fmt.Printf("index:%d\tvalue:%s\n",i,b[i])
   }
}

Two-dimensional arrays and traversal

func doubleArray() {
   var a[3][2]string = [3][2]string{
      {"lion","tiger"},
      {"cat","dog"},
      {"pig","pigwan"},
   }
   fmt.Println(a)
}
func printArray(a[3][2]string) {
   for _,v1 := range a {
      for _,v2 := range v1 {
         fmt.Printf("%s\n",v2)
      }
      fmt.Printf("\n")
   }
}
func main() {
   loopArray()
   doubleArray()
   var b[3][2] string
   b[0][0] = "apple"
   b[0][1] = "banana"
   b[1][0] = "sumsung"
   b[1][1] = "huawei"
   b[2][0] = "eggplant"
   b[2][1] = "chicken"
   printArray(b)
}

Array Copies and References

  • Array is a value type
func transArray() {
   var a [3]int
   a[0] = 10
   a[1] = 20
   a[2] = 30
   b := a
   b[0] = 1000
   fmt.Println(a,b)
   fmt.Printf("%p\t%p\n",&a,&b)
}

func modifyB(b [3]int) {
   b[0] = 1000
   return
}

Section

Definition

  • One-tier encapsulation based on array type.Very flexible, expandable
  • Slice initialization, a[start:end] creates a slice that includes from start to end-1
  • Array is value type, slice is reference type
func modifySlice() {
   //Define Array
   darr := [...]int{157,89,90,82,100,78,67,69,59}
   // Create Slices
   dslice := darr[2:5]
   fmt.Printf("slice before %v\n",dslice)
   fmt.Printf("array before %v\n",darr)
   for i := range dslice {
      dslice[i] ++
   }
   fmt.Printf("array after %v\n",darr)
   fmt.Printf("after slice %v\n",dslice)
}

Basic operation of slicing

  • arr[start:end]: Includes all elements from start to end-1
  • arr[start:]: Includes all elements from the start to the last element
  • arr[:end]: Includes all elements from 0 to end-1
  • arr[:]: Includes all elements of the entire array

Create slices using make

func makeSlice() {
   i := make([]int,5,10)
   i[0] = 0
   i[1] = 1
   i[2] = 2
   i[3] = 3
   i = append(i, 5)   //append from Length+1
   i = append(i,6,7,8,9,10,11,12,13)   // Append multiple values to automatically expand capacity
   fmt.Printf("%v\tlen %d\tcap %d\n",i,len(i),cap(i))
}

Slice Copy

func rewriteSlice() {
   var a[]int = make([]int,5,5)
   b := a
   fmt.Printf("[Before modification) a Address%p,a Value of%v;b Address%p,b Value of%v\n",&a,a,&b,b)
   a = append(a,10)    //a's address and
   fmt.Printf("[After modification) a Address%p,a Value of%v;b Address%p,b Value of%v\n",&a,a,&b,b)
}

Reslicing of slices

func sliceAgain() {
   var a []int
   var b [6]int = [6]int{1,2,3,4,5,6}
   a = b[0:4]
   fmt.Printf("a Length%d,capacity%d,type%T\n",len(a),cap(a),a)
   c := b[1:4]
   fmt.Printf("c Length%d,capacity%d,type%T\n",len(c),cap(c),c)   //c is 3 in length and 5 in capacity, because starting with 1, there is one less b referencing the bottom

   d := a[0:2]
   fmt.Printf("d Length%d,capacity%d,type%T\n",len(d),cap(d),d)    //d is the re-slicing of a slice, so the capacity is the same as a, and the length is based on the intercepted length
}

Empty slice

var a []int    //Not initialized, no allocation of length and capacity (no memory space), so called empty slices, append can automatically expand, eliminating the initialization process, nil means an empty address
func noneSlice() {
   var name []string
   if name == nil {
      fmt.Printf("this is none slice %v\n",name)
      name = append(name, "wanghui","devops")
      fmt.Printf("none slice append value %v\n",name)
   }
}
// append of slice
func appendSlice() {
   var b []int = []int{1,2,3,4}
   var a []int
   a = append(a,b...)    //Append B to a (... is the meaning of the element that expands b)
}

Slice Pass-through

Prove that slices are reference passing

func transArgs(a []int) {
   fmt.Printf("%p\n",a)
   for i := range a{
      a[i] = 111
      fmt.Println(a[i])
   }
}

func main() {
   nums := []int{1,2,3,4}
   fmt.Printf("%p\n",nums)
   transArgs(nums)
   fmt.Printf("%p\n",nums)    // Parameters will be changed
}

Copy of Slice

copy(dest,src)
After copying, the respective addresses do not change, only the value of the copy destination changes

func copySlice() {
   a := []int{1,2,3}
   b := []int{7,8}
   copy(b,a)
   fmt.Printf("a=%v,len(a)=%d,addr(a)=%p\tb=%v,len(b)=%d,addr(b)=%p\n",
      a,len(a),&a,
      b,len(b),&b)
}

Homework and reference

  • Sum all elements of an array
func arraySum() {
   var arr [10]int
   for i:=0;i<len(arr);i++ {
      arr[i] = rand.Intn(10000)
   }

   var sum int
   for j:=0;j<len(arr);j++ {
      sum += arr[j]
   }
   fmt.Printf("arr is %v\nsum=%d\n",arr,sum)
}
  • Find subscripts in the array whose specified elements add up to 8
    For example, arr: = []int{1,3,5,8,7}, with subscripts of (0,4), (1,2)
func indexReturn() {
   //gen array
   var arr [10]int
   for i:=0;i<len(arr);i++ {
      arr[i] = i
   }
   //calc
   fmt.Println(arr)
   for i:=0;i<len(arr);i++ {
      for j:=i+1;j<len(arr);j++ {
         if (arr[j]+arr[i]==12) {
            fmt.Printf("arr Subscripts with a sum of 12 are i=%d,j=%d\n",i,j)
         }
      }
   }
}
  • Sorting arrays using the sort function
func useSort() {
   var arr [10]int
   for i:=0;i<len(arr);i++ {
      arr[i] = rand.Intn(10000)
   }

   fmt.Printf("before sort %v\n",arr)
   sort.Ints(arr[:])

   fmt.Printf("after sort %v\n",arr)
}
  • Implement a password generation tool that supports the following functions
    • Specify password length, default 16 bits
    • Use type selection to generate different types of passwords
package main

import (
   "flag"
   "fmt"
   "math/rand"
   "time"
)

var (
   numCharset = "0123456789"
   strCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
   mixCharset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
   advanceCharset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()"
)

func geneLetter() {
   //Get 26 letters
   start := 'A'
   for i:=0;i<26;i++{
      fmt.Printf("%c",start)
      start += 1
   }
}

func main() {
   var length int
   var charset string
   flag.IntVar(&length,"l",16,"-l the length of passwd")
   flag.StringVar(&charset,"t","mix","-t the charset of passwd")
   flag.Parse()

   rand.Seed(time.Now().UnixNano())

   var userCharset string

   switch charset {
   case "num":
      userCharset = numCharset
   case "char":
      userCharset = strCharset
   case "mix":
      userCharset = mixCharset
   case "advance":
      userCharset = advanceCharset
   default:
      userCharset = mixCharset
   }

   var password []byte
   for i:=0;i < length;i++ {
      index := rand.Intn(len(userCharset))
      char := userCharset[index]
      password = append(password,char)
   }
   strPassword := string(password)
   fmt.Printf("The generated password is%s\n",strPassword)
}

Tags: Go less

Posted on Sat, 14 Mar 2020 20:15:05 -0400 by TJMAudio