這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
golang的Map程式:
package mainimport "fmt"type e interface{}func mult2(t e) e {switch t.(type) {case int:return t.(int) * 2case string:return t.(string) + t.(string)}return t}func add3(t e) e {switch t.(type) {case int:return t.(int) + t.(int) + t.(int)case string:return t.(string) + t.(string) + t.(string)}return t}func localmap(s []e, f func(e) e) {s2 := make([]e, len(s))for k, v := range s {s2[k] = f(v)}fmt.Println(s2)}func main() {slice1 := []e{1, 2, 3, 4, "a", "hello"}slice2 := []e{"a", "b", "c"}localmap(slice1, mult2)localmap(slice2, mult2)localmap(slice1, add3)localmap(slice2, add3)}
運行結果:
[2 4 6 8 aa hellohello][aa bb cc][3 6 9 12 aaa hellohellohello][aaa bbb ccc]
要分清數組指標類型 *[n]T和指標數群組類型 [n]*T。用new建立數組,返回的是數組指標:
package mainimport "fmt"func test(a *[10]int) {a[2] = 100}func main() {var a = new([10]int)test(a)fmt.Println(a, len(a))}
golang的OOP樣本:
package mainimport "fmt"type User struct {Id intName string}type Manager struct {UserGroup string}type Tester interface {Test()}func (this *User) Test() {fmt.Println(this)}func (this *Manager) Test() {fmt.Println(this)}func dosometing(o Tester) {o.Test()}func main() {m := Manager{User: User{2, "jack"}, Group: "IT"}dosometing(&m)dosometing(&m.User)}
擁有超集的介面可以被轉換為子集的介面:
package mainimport "fmt"type User struct {Id intName string}type Manager struct {Group stringUser}type IUser interface {Test()}type IManager interface {Test()Test2()}func (this *User) Test() {fmt.Println(this)}func (this *Manager) Test2() {fmt.Println(this)}func main() {var im IManager = &Manager{"IT", User{1, "tom"}}im.Test()im.Test2()var iu IUser = imiu.Test()}
對於channel,首先要明確“發送(send)”與“接收(receive)”的概念:“發送是指”值傳遞給channel;“接收”是指從channel讀取值。可以定義僅能發送或僅能接收的單向channel。比如c1 chan<-int,僅能發送int類型的值給c1;c2 <-chan int,c2僅能接收int類型的值。樣本如下:
package mainimport ("fmt")func recv(i <-chan int, o chan<- bool) {for v := range i {fmt.Println(v)}o <- true}func send(i chan<- int) {for j := 0; j < 10; j++ {i <- j}close(i)}func main() {i := make(chan int)o := make(chan bool)go recv(i, o)go send(i)<-o}
使用channel實現訊號量:
package mainimport ("fmt""sync""time")var sem = make(chan int, 2)var wg = sync.WaitGroup{}func worker(i int) {sem <- 1fmt.Println(time.Now().Format("04:05"), i)time.Sleep(1 * time.Second)<-semwg.Done()}func main() {for i := 0; i < 10; i++ {wg.Add(1)go worker(i)}wg.Wait()}