zoukankan      html  css  js  c++  java
  • Go 常用的方法

    字符串相关:

    去掉首尾空格:

    方法 strings.TrimSpace():

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        s1 := "   hello world 你好 世界 "
        ret := strings.TrimSpace(s1)
        fmt.Println(ret)
    }
    View Code

    字符串和int 互转:

    func test()  {
        // int --> string
        a := 10
        ret := strconv.Itoa(a)
        fmt.Println(ret)
        fmt.Printf("%T
    ",ret)
    
        // string --> int
        b := "20"
        ret2,_ := strconv.Atoi(b)
        fmt.Println(ret2)
        fmt.Printf("%T
    ",ret2)
    }
    View Code
     

    字符串中是否含有某个子串:

    func main()  {
        s := "hello admin world"
        // s 是否 含有 admin
        ret := strings.Index(s,"admin") // 如果含有返回 首字符索引,反之返回-1  
        fmt.Println(ret)
    }
    View Code
    
    

    go的   path/filepath 包: 

    filepath包实现了兼容各操作系统的文件路径的实用操作函数

    拼接路径 Join 方法 :

    package main
    
    import (
        "fmt"
        "path/filepath"
    )
    func main() {
        ret := filepath.Join("./","static","fonts") 
        fmt.Println(ret)  
    }
    View Code

    返回当前的绝对路径:

    package main
    
    import (
        "fmt"
        "path/filepath"
    )
    func main() {
        ret,_ := filepath.Abs("static")
        fmt.Println(ret)
    }
    View Code

    go 的 math/rand 包:

    rand 包实现了伪随机数生成器

    随机数从资源生成。包水平的函数都使用的默认的公共资源。该资源会在程序每次运行时都产生确定的序列。如果需要每次运行产生不同的序列,应使用Seed函数进行初始化。默认资源可以安全的用于多go程并发。

    详情参考: https://studygolang.com/static/pkgdoc/pkg/math_rand.htm

    package main
    
    import (
        "fmt"
        "math/rand"
        "time"
    )
    func main() {
        rand.Seed((int64(time.Now().Second())))
        ret := rand.Intn(10) // [0-10) 的随机数
        fmt.Println(ret)
    }
    产生 [0-10) 的随机数

    go 的 encoding/gob 包:

    详情参考: https://www.cnblogs.com/yjf512/archive/2012/08/24/2653697.html 

     https://studygolang.com/static/pkgdoc 中的 encoding/gob 包,

  • 相关阅读:
    36、【opencv入门】运动物体检测(2)
    二叉树数
    多边形的三角划分
    乘积最大
    加分二叉树
    c++ 装箱问题
    生物基元问题
    一般性的最少硬币组成问题
    打包
    挤牛奶
  • 原文地址:https://www.cnblogs.com/zach0812/p/12799308.html
Copyright © 2011-2022 走看看