zoukankan      html  css  js  c++  java
  • golang基础语法

    type inter interface{
        //不写变量,函数 是个空接口
        }
    #任何其他类型的数据都可以赋值给interface{}类型。
    ex: a := []byte('abc')
    
    
    func main() {
        m := make(map[string]int, 99)
        cap(m) //error
    }
    # command-line-arguments
    ./hello.go:5: invalid argument m (type map[string]int) for cap
    先来看一下go的内置函数cap与map:
    cap: 返回的是数组切片分配的空间大小, 根本不能用于map
    make: 用于slice,map,和channel的初始化
    
    要获取map的容量,可以用len函数。
    1.断言:判断变量的类型
    var a interface{}
    rc,ok := a.(interface{}) []byte []rune 类似python的isdigit等,返回bool值
    rc a的值,ok是断言的bool值


    golang之间数据转换

    一、基本数据类型之间的转换

    
    

    1、string到int  

    *****导入模块strconv模块****

    int,err:=strconv.Atoi(string)  

    
    

    2、string到int64  

    
    

    int64, err := strconv.ParseInt(string, 10, 64)  

    
    

    3、int到string  

    
    

    string:=strconv.Itoa(int)  

    
    

    4、int64到string  

    
    

    string:=strconv.FormatInt(int64,10)  

    
    

    5、字符串到float32/float64

    
    

    float32, err = ParseFloat(string, 32)  

    
    

    float64,err = ParseFloat(string,64)

    
    

    6、int64转int

    
    

    int:=int(int64)  

    
    

    7、int转int64

    
    

    int64:=int64(int)

    
    

    二、interface{}与其他类型之间的转换

    
    

    转换方式包括隐式转换与断言转换。

    
    

    1、interface{}类型转换成具体类型:interfaceVar.(具体类型)

    
    

    原理:断言实现。如:

    
    

    断言成功返回true,失败返回false

    
    
    value, ok := a.(string)
    if !ok {
        fmt.Println("It's not ok for type string")
        return
    }
    fmt.Println("The value is ", value)
    
    

    2、具体类型可以隐式转换成interface{}类型

    
    

    3、string与[]byte之间的转换:

    
    

    string到[]byte:字节数组=[]byte(字符串)

    
    

    字节数组到string: 字符串=string([]byte)

     

    golang for循环 break continue 标签

    example:

    LABEL1:
    for i := 0; i <= 5; i++ {
    for j := 0; j <= 5; j++ {
    if j == 4 {
    goto LABEL1 //continue(打上标签,作用是可以跳出多层循环)调到标记处继续执行,状态是上次的延续 i=1
                   //goto 则是重新执行标签下代码,变量初始化
                   //break 跳出标签-break的所有循环 类似于return (return则是终止程序,break则是跳出标签下循环,继续往下执行)
    }
    fmt.Printf("i is: %d, and j is: %d ", i, j)
    }
    }
    关于nil值的判断
    //pointer(指针), channel(管道), func, interface, map, or slice 这些类型的值才可以是nil.
  • 相关阅读:
    jmeter(46) redis
    jmeter(45) tcp/ip协议
    Codeforces Round #538 (Div. 2)D(区间DP,思维)
    Codeforces Global Round 1D(DP,思维)
    Educational Codeforces Round 57D(DP,思维)
    UPC11073(DP,思维)
    Yahoo Progamming Contest 2019D(DP,思维)
    Atcoder Beginner Contest 118D(DP,完全背包,贪心)
    Xuzhou Winter Camp 1C(模拟)
    Educational Codeforces Round 57 (Rated for Div. 2)D(动态规划)
  • 原文地址:https://www.cnblogs.com/qlshao/p/12625197.html
Copyright © 2011-2022 走看看