1. 程式人生 > >【go語言 基礎系列】內建函式

【go語言 基礎系列】內建函式

原始檔builtin.go檔案中一共定義了15個內建函式,go1.9.2 版本。通過函式名可以直接呼叫函式。

  • func append(slice []Type, elems ...Type) []Type
  • func copy(dst, src []Type) int
  • func delete(m map[Type]Type1, key Type)
  • func len(v Type) int
  • func cap(v Type) int
  • func make(t Type, size ...IntegerType) Type
  • func new(Type) *Type
  • func complex(r, i FloatType) ComplexType
  • func real(c ComplexType) FloatType
  • func imag(c ComplexType) FloatType
  • func close(c chan<- Type)
  • func panic(v interface{})
  • func recover() interface{}
  • func print(args ...Type)
  • func println(args ...Type)

【append】

將資料追加到slice的末尾,返回一個slice

125 // The append built-in function appends elements to the end of a slice. If
126 // it has sufficient capacity, the destination is resliced to accommodate the
127 // new elements. If it does not, a new underlying array will be allocated.
128 // Append returns the updated slice. It is therefore necessary to store the
129 // result of append, often in the variable holding the slice itself:
130 //      slice = append(slice, elem1, elem2)
131 //      slice = append(slice, anotherSlice...)
132 // As a special case, it is legal to append a string to a byte slice, like this:
133 //      slice = append([]byte("hello "), "world"...)
134 func append(slice []Type, elems ...Type) []Type

函式呼叫demo

package main

import (
        "fmt"
)

func main() {
        var a []string
        b := append(a, "x")
        fmt.Println(b)

        c := append(b, "y")
        fmt.Println(c)

        d := append(c, "z", "X", "Y", "Z")
        fmt.Println(d)

        fmt.Println(a, b, c, d)

        str := append([]byte("hello "), "world"...)

        fmt.Println(str)
        fmt.Printf("%s", str)
}

【copy】

copy把源slice的資料複製到目的slice中,當目的slice的空不夠的時候會捨棄超出的部分,返回的是複製成功的元素個數

136 // The copy built-in function copies elements from a source slice into a
137 // destination slice. (As a special case, it also will copy bytes from a
138 // string to a slice of bytes.) The source and destination may overlap. Copy
139 // returns the number of elements copied, which will be the minimum of
140 // len(src) and len(dst).
141 func copy(dst, src []Type) int

函式呼叫demo

package main

import (
	"fmt"
)

func main() {
	strs := []string{"a", "b", "c", "d"}
	strd := []string{"A", "B", "C"}
	fmt.Println("before")
	fmt.Println("strs is:", strs)
	fmt.Println("strd is:", strd)
	n := copy(strd, strs)

	fmt.Println("after  copy(strd,strs):")
	fmt.Println("strs is:", strs)
	fmt.Println("strd is:", strd)
	fmt.Println("n is:", n)

	var str1 []string
	var str2 []string

	str1 = []string{"aa", "bb", "cc", "dd", "ee"}
	m := copy(str2, str1)
	fmt.Println("m is:", m)
	fmt.Println("str2 is:", str2)

	str3 := make([]string, 3)
	m2 := copy(str3, str1)
	fmt.Println("m2 is:", m2)
	fmt.Println("str3 is:", str3)

}

執行結果

before
strs is: [a b c d]
strd is: [A B C]
after  copy(strd,strs):
strs is: [a b c d]
strd is: [a b c]
n is: 3
m is: 0
str2 is: []
m2 is: 3
str3 is: [aa bb cc]
 

【delete】

delete函式用於刪除map中對應key的value。

143 // The delete built-in function deletes the element with the specified key
144 // (m[key]) from the map. If m is nil or there is no such element, delete
145 // is a no-op.
146 func delete(m map[Type]Type1, key Type)

函式呼叫demo

package main

import (
	"fmt"
)

func main() {
	var mp = map[string]int{
		"a": 1,
		"b": 2,
		"c": 3,
	}
	fmt.Println(mp)
	delete(mp, "b")
	fmt.Println(mp)
	delete(mp, "e")
	fmt.Println(mp)

}

【len】

陣列,slice  map string channel等型別的長度如下面demo

148 // The len built-in function returns the length of v, according to its type:
149 //      Array: the number of elements in v.
150 //      Pointer to array: the number of elements in *v (even if v is nil).
151 //      Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
152 //      String: the number of bytes in v.
153 //      Channel: the number of elements queued (unread) in the channel buffer;
154 //      if v is nil, len(v) is zero.
155 func len(v Type) int

函式呼叫demo

package main

import (
	"fmt"
)

func main() {
	arrint := []int{11, 22, 33}
	arrstr := []string{"aa", "bb", "cc", "11"}
	fmt.Println("len(arrint) is:", len(arrint))
	fmt.Println("len(arrstr) is:", len(arrstr))

	str := "abcde"
	fmt.Println("len(str) is:", len(str))

	var ch = make(chan int, 5)
	ch <- 1
	ch <- 2
	fmt.Println("len(ch) is:", len(ch))

	var mp map[string]int = map[string]int{
		"a": 1,
		"b": 2,
		"c": 3,
	}
	fmt.Println("len(mp) is:", len(mp))
}

執行結果如下

len(arrint) is: 3
len(arrstr) is: 4
len(str) is: 5
len(ch) is: 2
len(mp) is: 3
【cap】

cap()計算 陣列 slice channel 型別的容量。沒有map

157 // The cap built-in function returns the capacity of v, according to its type:
158 //      Array: the number of elements in v (same as len(v)).
159 //      Pointer to array: the number of elements in *v (same as len(v)).
160 //      Slice: the maximum length the slice can reach when resliced;
161 //      if v is nil, cap(v) is zero.
162 //      Channel: the channel buffer capacity, in units of elements;
163 //      if v is nil, cap(v) is zero.
164 func cap(v Type) int

函式呼叫demo

package main

import (
	"fmt"
)

func main() {
	var arr [10]string = [10]string{"a", "b", "c"}
	fmt.Println("arr is:", arr, "cap(arr) is:", cap(arr))

	var slice []string = []string{"a", "b", "c"}
	fmt.Println("slice is:", slice, "cap(slice) is:", cap(slice))

	var ch = make(chan int, 10)
	ch <- 1
	ch <- 2
	fmt.Println("cap(ch) is:", cap(ch))
}

執行結果

arr is: [a b c       ] cap(arr) is: 10
slice is: [a b c] cap(slice) is: 3
cap(ch) is: 10
【make】

make()給slice map  channel 分配容量空間,其中slice 可以指定長度,map無效。map的空間一般與系統記憶體有關。

166 // The make built-in function allocates and initializes an object of type
167 // slice, map, or chan (only). Like new, the first argument is a type, not a
168 // value. Unlike new, make's return type is the same as the type of its
169 // argument, not a pointer to it. The specification of the result depends on
170 // the type:
171 //      Slice: The size specifies the length. The capacity of the slice is
172 //      equal to its length. A second integer argument may be provided to
173 //      specify a different capacity; it must be no smaller than the
174 //      length, so make([]int, 0, 10) allocates a slice of length 0 and
175 //      capacity 10.
176 //      Map: An empty map is allocated with enough space to hold the
177 //      specified number of elements. The size may be omitted, in which case
178 //      a small starting size is allocated.
179 //      Channel: The channel's buffer is initialized with the specified
180 //      buffer capacity. If zero, or the size is omitted, the channel is
181 //      unbuffered.
182 func make(t Type, size ...IntegerType) Type

函式呼叫demo

package main

import (
	"fmt"
)

func main() {
	var slice1 = make([]string, 0, 10)
	var slice2 = make([]string, 5, 10)
	fmt.Println("len(slice1) is", len(slice1), "cap(slice1) is:", cap(slice1))
	fmt.Println("len(slice2) is", len(slice2), "cap(slice2) is:", cap(slice2))

	var mp = make(map[string]int)
	fmt.Println("len(mp) is:", len(mp))

	var ch1 = make(chan int)
	var ch2 = make(chan int, 10)
	fmt.Println("len(ch1) is:", len(ch1), "cap(ch1) is", cap(ch1))
	fmt.Println("len(ch2) is:", len(ch2), "cap(ch2) is", cap(ch2))
	ch2 <- 11
	ch2 <- 22
	fmt.Println("len(ch1) is:", len(ch1), "cap(ch1) is", cap(ch1))
	fmt.Println("len(ch2) is:", len(ch2), "cap(ch2) is", cap(ch2))

}

執行結果

len(slice1) is 0 cap(slice1) is: 10
len(slice2) is 5 cap(slice2) is: 10
len(mp) is: 0
len(ch1) is: 0 cap(ch1) is 0
len(ch2) is: 0 cap(ch2) is 10
len(ch1) is: 0 cap(ch1) is 0
len(ch2) is: 2 cap(ch2) is 10
【new】

new()返回的是對應型別的指標

184 // The new built-in function allocates memory. The first argument is a type,
185 // not a value, and the value returned is a pointer to a newly
186 // allocated zero value of that type.
187 func new(Type) *Type

函式呼叫demo

package main

import (
	"fmt"
)

func main() {
	i := new(int)
	s := new(string)
	arr := new([5]string)
	slice := new([]string)
	mp := new(map[string]string)
	ch := new(chan int)
	fmt.Printf("i type is %T\n", i)
	fmt.Printf("s type is %T,len is %v\n", s, len(*s))
	fmt.Printf("arr type is %T,len is %v\n", arr, len(*arr))
	fmt.Printf("slice type is %T,len is %v\n", slice, len(*slice))
	fmt.Printf("mp type is %T,len is %v\n", mp, len(*mp))
	fmt.Printf("ch type is %T,len is %v\n", ch, len(*ch))
}

【complex,real,imag,close 略】

【panic及recover 後續詳細講解】

【print 及println 】

239 // The print built-in function formats its arguments in an
240 // implementation-specific way and writes the result to standard error.
241 // Print is useful for bootstrapping and debugging; it is not guaranteed
242 // to stay in the language.
243 func print(args ...Type)
244 
245 // The println built-in function formats its arguments in an
246 // implementation-specific way and writes the result to standard error.
247 // Spaces are always added between arguments and a newline is appended.
248 // Println is useful for bootstrapping and debugging; it is not guaranteed
249 // to stay in the language.
250 func println(args ...Type)