日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【Go基础】03 包 标准库

發(fā)布時(shí)間:2024/3/26 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Go基础】03 包 标准库 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

目錄

  • 1. 包
    • 1.1. 工作空間
    • 1.2. 源文件
    • 1.3. 包結(jié)構(gòu)
      • 1.3.1. 包結(jié)構(gòu) 規(guī)則
      • 1.3.2. 區(qū)分
      • 1.3.3. 導(dǎo)入包
  • 2. os
    • 2.1. 文件操作
    • 2.2. os/exec
  • 3. fmt
    • 3.1. 格式化輸出
    • 3.2. println
  • 4. log
    • 4.1. 包結(jié)構(gòu)
    • 4.2. 日志輸出
  • 5. 字符串處理
    • 5.1. 字符(串)轉(zhuǎn)換
      • 5.1.1. 字符串長度
    • 5.2. 字符串運(yùn)算
      • 5.2.1. 常用函數(shù)
  • 6. 指針
    • 6.1. unsafe
    • 6.2. 內(nèi)存對齊問題:
  • 7. 時(shí)間處理 time
    • 7.1. time

學(xué)習(xí)資料
書籍:

  • Go學(xué)習(xí)筆記–github雨痕
  • Go語言入門教程,Golang入門教程

  • 1. 包

  • 應(yīng)該花時(shí)間看一下標(biāo)準(zhǔn)庫中提供了些什么,以及它是如何實(shí)現(xiàn)的
  • 不僅要防止重新造輪子,還要理解 Go 語言的設(shè)計(jì)者的習(xí)慣,并將這些習(xí)慣應(yīng)用到自己的包和 API 的設(shè)計(jì)上。

  • 1.1. 工作空間


    1.2. 源文件


    1.3. 包結(jié)構(gòu)

    1.3.1. 包結(jié)構(gòu) 規(guī)則

  • 命名

  • 給包及其目錄命名時(shí),應(yīng)該使用簡潔、清晰且全小寫的名字,這有利于開發(fā)時(shí)頻繁輸入包名。
  • 包名與代碼所在的文件夾同名;
  • 包中成員以名稱大小寫決定訪問權(quán)限。

  • public: 首字母大寫,可被包外訪問。
  • internal: 首字母小寫,僅包內(nèi)成員可以訪問。
  • 代碼示例:

    // counters包 提供告警計(jì)數(shù)器功能 package counters//alterCounter是一個(gè)未公開的類型 // 用于保存告警計(jì)數(shù)器 type alterCounter int //--小寫字母開頭, 包外不可見, type AlterCounter int //--大寫字母開頭, 包外可見//
  • 解決辦法
  • 使用工廠函數(shù)來創(chuàng)建一個(gè)未公開的alterCounter類型的值;
  • 說明:

  • os.Args 返回命令行參數(shù),os.Exit 終止進(jìn)程。
  • 要獲取正確的可執(zhí)??件路徑,可用 filepath.Abs(exec.LookPath(os.Args[0]))
  • 參考:

  • go語言實(shí)戰(zhàn)
  • 1.3.2. 區(qū)分

  • java與go main()與package的區(qū)別
  • 在java中,任何一個(gè)java文件都可以有唯一一個(gè)main方法當(dāng)做啟動(dòng)函數(shù)
  • S在go中,則是任何一個(gè)package中,都可以有唯一一個(gè)帶有main方法的go文件
  • 1.3.3. 導(dǎo)入包

    • 包管理// go mod go mod init go_demo
  • go module// 導(dǎo)入多個(gè)包import ("log""runtime") // 別名導(dǎo)入包import F "fmt"-- 相當(dāng)于給包 fmt 起了個(gè)別名 F ,用 F.代替標(biāo)準(zhǔn)的 fmt.作為前綴引用 fmt 包內(nèi)可導(dǎo)出元素。 // 遠(yuǎn)程導(dǎo)入包import "github.com/net/http" // 僅執(zhí)行初始化init函數(shù) 導(dǎo)入import _ "fmt"-- 下劃線字符 _在 Go 語言里稱為空白標(biāo)識(shí)符,這個(gè)標(biāo)識(shí)符用來拋棄不想繼續(xù)使用的值 // 省略引用import . "fmt"// 替換包 require "liwenzhou.com/q1mi/p2" v0.0.0 replace "liwenzhou.com/q1mi/p2" => "../p2" // --替換包
  • 參考:

  • Go 學(xué)習(xí)筆記(3)— 包概念、包特點(diǎn)、包名約束、main 包、包的聲明、包的引用、包初始化

  • 2. os

    • 概述:
    • 操作文件主要由兩個(gè)標(biāo)準(zhǔn)庫: os 和 ioutil
    • os庫 主要用于操作文件, 主要用于操作系統(tǒng)功能;

    2.1. 文件操作

  • 常用函數(shù):
  • // 1. 創(chuàng)建文件// 2. 打開文件// 3. 寫入文件// 4. 讀取文件// 5. 刪除文件// 6. 關(guān)閉文件

    2.2. os/exec

    • 概述:
    • exec包執(zhí)行外部命令。它包裝了os.StartProcess函數(shù)以便更容易的修正輸入和輸出,使用管道連接I/O,以及作其它的一些調(diào)整。

    參考:

  • os/exec
  • Go 學(xué)習(xí)筆記(43)— Go 標(biāo)準(zhǔn)庫之 os/exec(執(zhí)行外部命令、非阻塞等待、阻塞等待、命令輸出)

  • 3. fmt


    3.1. 格式化輸出

    • 格式:
    General:%v the value in a default formatwhen printing structs, the plus flag (%+v) adds field names%#v a Go-syntax representation of the value%T a Go-syntax representation of the type of the value%% a literal percent sign; consumes no valueBoolean:%t the word true or falseInteger:%b base 2%c the character represented by the corresponding Unicode code point%d base 10%o base 8%O base 8 with 0o prefix%q a single-quoted character literal safely escaped with Go syntax.%x base 16, with lower-case letters for a-f%X base 16, with upper-case letters for A-F%U Unicode format: U+1234; same as "U+%04X"Floating-point and complex constituents:%b decimalless scientific notation with exponent a power of two,in the manner of strconv.FormatFloat with the 'b' format,e.g. -123456p-78%e scientific notation, e.g. -1.234456e+78%E scientific notation, e.g. -1.234456E+78%f decimal point but no exponent, e.g. 123.456%F synonym for %f%g %e for large exponents, %f otherwise. Precision is discussed below.%G %E for large exponents, %F otherwise%x hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20%X upper-case hexadecimal notation, e.g. -0X1.23ABCP+20String and slice of bytes (treated equivalently with these verbs):%s the uninterpreted bytes of the string or slice%q a double-quoted string safely escaped with Go syntax%x base 16, lower-case, two characters per byte%X base 16, upper-case, two characters per byteSlice:%p address of 0th element in base 16 notation, with leading 0xPointer:%p base 16 notation, with leading 0xThe %b, %d, %o, %x and %X verbs also work with pointers,formatting the value exactly as if it were an integer.The default format for %v is:bool: %tint, int8 etc.: %duint, uint8 etc.: %d, %#x if printed with %#vfloat32, complex64, etc: %gstring: %schan: %ppointer: %pFor compound objects, the elements are printed using these rules, recursively, laid out like this:struct: {field0 field1 ...}array, slice: [elem0 elem1 ...]maps: map[key1:value1 key2:value2 ...]pointer to above: &{}, &[], &map[]Width is specified by an optional decimal number immediately preceding the verb. If absent, the width is whatever is necessary to represent the value. Precision is specified after the (optional) width by a period followed by a decimal number. If no period is present, a default precision is used. A period with no following number specifies a precision of zero. Examples:%f default width, default precision%9f width 9, default precision%.2f default width, precision 2%9.2f width 9, precision 2%9.f width 9, precision 0

    參考:

  • Package fmt

  • 3.2. println

  • 內(nèi)置的print/println函數(shù)總是寫入標(biāo)準(zhǔn)錯(cuò)誤。 fmt標(biāo)準(zhǔn)包里的打印函數(shù)總是寫入標(biāo)準(zhǔn)輸出。
  • 參考:

  • 官方文檔: 格式化輸出printf
  • print

  • 4. log

    參考:

  • 書籍: go語言實(shí)戰(zhàn)
  • 4.1. 包結(jié)構(gòu)

  • log包日志記錄器 是多routine安全的;
  • 4.2. 日志輸出

  • 格式及標(biāo)志符

    func init() {//log.SetPrefix("TRACE: ")log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile) }func main() {// Println 寫到標(biāo)準(zhǔn)日志記錄器 --格式化輸出函數(shù): 去掉 ln + flog.Println("message")// Fatalln 在調(diào)用 Println()之后會(huì)接著調(diào)用 os.Exit(1)log.Fatalln("fatal message")// Panicln 在調(diào)用 Println()之后會(huì)接著調(diào)用 panic()log.Panicln("panic message") }//輸出: TRACE: 2021/04/19 18:55:55.188845 D:/GO/src/code.practise/test_log/test_log1.go:15: message TRACE: 2021/04/19 18:55:55.297291 D:/GO/src/code.practise/test_log/test_log1.go:18: fatal message//== 相關(guān)結(jié)構(gòu)體 const (Ldate = 1 << iota // the date in the local time zone: 2009/01/23Ltime // the time in the local time zone: 01:23:23Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.Llongfile // full file name and line number: /a/b/c/d.go:23Lshortfile // final file name element and line number: d.go:23. overrides LlongfileLUTC // if Ldate or Ltime is set, use UTC rather than the local time zoneLmsgprefix // move the "prefix" from the beginning of the line to before the messageLstdFlags = Ldate | Ltime // initial values for the standard logger )// 自定義logger Trace = log.New(ioutil.Discard,"TRACE: ",log.Ldate|log.Ltime|log.Lshortfile)Info = log.New(os.Stdout,"INFO: ",log.Ldate|log.Ltime|log.Lshortfile)Warning = log.New(os.Stdout,"WARNING: ",log.Ldate|log.Ltime|log.Lshortfile)Error = log.New(io.MultiWriter(file, os.Stderr),"ERROR: ",log.Ldate|log.Ltime|log.Lshortfile)
  • 不同日志方法的聲明

    func (l *Logger) Fatal(v ...interface{}) func (l *Logger) Fatalf(format string, v ...interface{}) func (l *Logger) Fatalln(v ...interface{}) func (l *Logger) Flags() int func (l *Logger) Output(calldepth int, s string) error func (l *Logger) Panic(v ...interface{}) func (l *Logger) Panicf(format string, v ...interface{}) func (l *Logger) Panicln(v ...interface{}) func (l *Logger) Prefix() string func (l *Logger) Print(v ...interface{}) func (l *Logger) Printf(format string, v ...interface{}) func (l *Logger) Println(v ...interface{}) func (l *Logger) SetFlags(flag int) func (l *Logger) SetPrefix(prefix string)

  • 5. 字符串處理

    • 常用的字符串處理包:

    • strconv – 類型轉(zhuǎn)換
    • strings – 字符運(yùn)算
    • 比較

    • 沒有其他語言中豐富的封裝函數(shù)(方法); --使用標(biāo)準(zhǔn)庫文件
    • 字符串概述

    • golang當(dāng)中的字符串本質(zhì)是只讀的字符型數(shù)組,不能通過下標(biāo)進(jìn)行修改;
    • 和C語言當(dāng)中的char[]類似,但是golang為它封裝了一個(gè)變量類型,叫做string。

    5.1. 字符(串)轉(zhuǎn)換

    • 方法:
    • 常用 strconv包;

    5.1.1. 字符串長度

  • 計(jì)算字符串長度:

    str := "hello 世界" fmt.Println(len(str)) //12 utf8: 一個(gè)漢字, 3個(gè)字節(jié);str := "hello 世界" fmt.Println(len([]rune(str))) //8
  • 字符串轉(zhuǎn)換為 byte數(shù)組, 灰產(chǎn)出國內(nèi)存拷貝嗎?

  • 會(huì), 嚴(yán)格來說, 只要發(fā)生類型轉(zhuǎn)換都會(huì)發(fā)生內(nèi)存拷貝;
  • 如何節(jié)省內(nèi)存操作, 以提升性能?// stringHeader 的地址 強(qiáng)轉(zhuǎn)成 SliceHeader ==> 底層轉(zhuǎn)換二者;a := "aaa"ssh := *(*reflect.StringHeader)(unsafe.Pointer(&a))b := *(*[]byte)(unsafe.Pointer(&ssh))

  • 5.2. 字符串運(yùn)算

    • 方法:
    • strings 標(biāo)準(zhǔn)庫;

    5.2.1. 常用函數(shù)

    ==: 具體查看包內(nèi)實(shí)現(xiàn); // 1.字符串比較cmp := strings.Compare(str1, str2) // 2. 查找函數(shù)var theInd = strings.Index(str, "sub")var theLastIdx = strings.LastIndex(str, "last") //返回出現(xiàn)的最后一個(gè)位置;// Count和Repeat ==>次數(shù)統(tǒng)計(jì)strings.Count("abcabcabababc", "abc") //統(tǒng)計(jì)子字符串出現(xiàn)次數(shù)repeat := strings.Repeat("abc", 10) //abcabcabcabcabcabcabcabcabcabc// Replace、Split和Join 替換, 拆分, 組裝str := "abc,bbc,bbd"slice := strings.Split(str, ",")slice := []string{"aab", "aba", "baa"}str := strings.Join(slice, ",")

    6. 指針

    • 包:
    • unsafe: 可以參與指針運(yùn)算;

    6.1. unsafe

  • 使用注意:

    任何類型的指針值都可以轉(zhuǎn)換為Pointer // unsafe.Pointer(&a1) Pointer可以轉(zhuǎn)換為任何類型的指針值 // (*float32)(unsafe.Pointer(numPointer)) uintptr可以轉(zhuǎn)換為 Pointer // unsafe.Pointer(uintptr(nPointer) + + unsafe.Sizeof(&a) * 3) Pointer可以轉(zhuǎn)換為 uintptr // uintptr(unsafe.Pointer(numPointer))
  • 相關(guān)函數(shù)

    // 返回類型所占的字節(jié)數(shù) func Sizeof(x ArbitraryType) uintptr // 返回結(jié)構(gòu)體中某個(gè)字段的偏移量; 字段需是 struct.field 形式//返回值: 結(jié)構(gòu)體變量開始位置到該字段的開始位置 func Offsetof(x ArbitraryType) uintptr // 返回內(nèi)存對齊時(shí)的對齊值; func Alignof(x ArbitraryType) uintptrreflect.TypeOf(bool(true)).Align()) 也可以計(jì)算內(nèi)存對齊值;
  • 實(shí)際使用場景:

  • // 1. 數(shù)據(jù)類型轉(zhuǎn)換func Float64bits(f float64) uint64 {return *(*uint64)(unsafe.Pointer(&f))}

    6.2. 內(nèi)存對齊問題:

    • 對齊規(guī)則1. 結(jié)構(gòu)體的成員變量,第一個(gè)成員變量的偏移量為 0。往后的每個(gè)成員變量的對齊值必須為編譯器默認(rèn)對齊長度(#pragma pack(n))或當(dāng)前成員變量類型的長度(unsafe.Sizeof),取最小值作為當(dāng)前類型的對齊值。其偏移量必須為對齊值的整數(shù)倍 2. 結(jié)構(gòu)體本身,對齊值必須為編譯器默認(rèn)對齊長度(#pragma pack(n))或結(jié)構(gòu)體的所有成員變量類型中的最大長度,取最大數(shù)的最小整數(shù)倍作為對齊值 3. 結(jié)合以上兩點(diǎn),可得知若編譯器默認(rèn)對齊長度(#pragma pack(n))超過結(jié)構(gòu)體內(nèi)成員變量的類型最大長度時(shí),默認(rèn)對齊長度是沒有任何意義的 ==

    參考:


  • 7. 時(shí)間處理 time

    import "time"

    7.1. time

    參考:

  • golang的timer一些坑

  • 總結(jié)

    以上是生活随笔為你收集整理的【Go基础】03 包 标准库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。