Golang初級-"hello world!"

Go

  • 趨勢
  1.  完全使用Go開發的項目

               容器:docker、kubernetes

               web server:caddy

               db:cockroachDb(new sql db)

      2.部分使用Go開發的項目 

                MongoDB/Couchbase

                 Dropbox

                 Uber

                 Google

  • 設計
  1. 類型檢查:編譯時
  2. 運行環境:編譯成機器代碼直接運行
  3. 編程範式:面向接口、函數式編程、併發編程

         併發編程:採用CSP(communication sequential process)模型,CSP的特點是不需要鎖,不需要callback。

                           編髮編程包括分佈式和並行計算

  • 安裝
  1. https://studygolang.com/dl 下載適合自己機器的golang版本
  2. Golang 在 Mac Vscode 中代碼自動補全和自動導入包:使用快捷鍵:command+shift+P:go:install/updatetools,將所有17個插件都勾選上,點擊ok即開始安裝。然後就可以使用了。
  • hello world server(讀取url的參數)
package main            

import (                //引入
	"fmt"
	"net/http"
)

func main() {
    //param  值 指針
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		fmt.Fprintf(writer, "<h1>hello world  %s!</h1>", request.FormValue("name"))
	})

    //監聽8888端口 阻塞監聽
	http.ListenAndServe(":8888", nil)
}
  •        hello world 併發版本(goroutine)
package main

import (
	"fmt"
	// "time"
)

//開啓goroutine 開啓chan類型數據通道,通過for循環來讓5000個goroutine來競爭輸出到主函數中的管道中
func main() {
	ch := make(chan string)
	for i := 0; i < 5000; i++ {
		//當加入go關鍵字後 starts a goroutine(go rui tin)
		go printHelloWorld(i, ch)

	}

	for {
		msg := <-ch
		fmt.Println(msg)
	}

	//延時5毫秒
	// time.Sleep(time.Millisecond)

}

func printHelloWorld(i int, ch chan string) {
	ch <- fmt.Sprintf("hello world form goroutine %d!\n", i)
}
  • go sort函數排序
package main

import (
	"fmt"
	"sort"
)

func main() {
	//create a slice of int 比數組更加靈活可以動態添加刪除等等操作
	arr := []int{3, 6, 2, 1, 9, 10, 8}
	sort.Ints(arr)
	for _, v := range arr {
		fmt.Println(v)
	}
}

 

發佈了49 篇原創文章 · 獲贊 3 · 訪問量 9336
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章