zoukankan      html  css  js  c++  java
  • [Go语言]从Docker源码学习Go——if语句和map结构

    if语句

    继续看docker.go文件的main函数

    if reexec.Init() {
            return
        }

    go语言的if不需要像其它语言那样必须加括号,而且,可以在判断以前,增加赋值语句

    语法

    IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .

    例子

    if x := f(); x < y {
        return x
    } else if x > z {
        return z
    } else {
        return y
    }

    map结构

    继续跟到reexec.Init()方法里面,文件位于docker/reexec/reexec.go

    var registeredInitializers = make(map[string]func())
    
    ...
    
    // Init is called as the first part of the exec process and returns true if an
    // initialization function was called.
    func Init() bool {
        initializer, exists := registeredInitializers[os.Args[0]]
        if exists {
            initializer()
    
            return true
        }
    
        return false
    }

    可以看到registeredInitializers是一个map类型,键类型为string,值类型为func().

    map的初始化是通过make()来进行, make是go的内置方法。

    除了通过make, 还可以通过类似下面的方法进行初始化

    mapCreated := map[string]func() int {
                            1: func() int {return 10},
                            2: func() int {return 20},
                            3: func() int {return 30},
                        }

    继续通过代码看map的使用

    initializer, exists := registeredInitializers[os.Args[0]]

    map[keyvalue]返回两个值,先看第二个,代表是否存在,第一个是在存在的情况下取得value的值,此处也就是取得这个func().

    再后面的代码就是判断是否存在,如果存在就执行取得的func().

    如果我们不想取value的值,只想判断是否存在,可以通过加下划线_的方式来忽略返回,比如

    _, exists := xxx

  • 相关阅读:
    django ORM
    django扩展知识
    django视图层
    php常用四种算法
    文件操作函数
    PHP开发中数组操作大全
    php 字符 常用函数
    MySQL的WHERE语句中BETWEEN与IN的用法和他们的区别
    $_SERVER
    PHP魔术方法和魔术常量
  • 原文地址:https://www.cnblogs.com/lemonbar/p/3922968.html
Copyright © 2011-2022 走看看