golang的一些實驗小程式

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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()}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.