美文网首页
defer 也没那么难

defer 也没那么难

作者: 追风骚年 | 来源:发表于2021-06-23 15:26 被阅读0次

    示例1

    func Test1() {
    str := "defer1"
        defer fmt.Println(str)
    
        str = "defer2"
        defer func() {
            fmt.Println(str)
        }()
    
        str = "defer3"
        defer func(str string) {
            fmt.Println(str)
        }(str)
        str = "defer4"
    }
    

    示例2

    func Test2() {
    
        str := []int{1}
        defer fmt.Println(str)
    
        str[0] = 2
        defer func() {
            fmt.Println(str)
        }()
    
        str[0] = 3
        defer func(str []int) {
            fmt.Println(str)
        }(str)
    
        str[0] = 4
    }
    
    

    示例3

    func Test3() {
    
        str := []int{1}
        defer fmt.Println(str)
    
        str = []int{2}
        defer func() {
            fmt.Println(str)
        }()
    
        str = []int{3}
        defer func(str []int) {
            fmt.Println(str)
        }(str)
    
        str = []int{4}
    }
    

    三个示例各有千秋,懂了就真的懂了

    相关文章

      网友评论

          本文标题:defer 也没那么难

          本文链接:https://www.haomeiwen.com/subject/zrubyltx.html