V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
agzero
V2EX  ›  Go 编程语言

golang 在方法的返回值中声明变量名,和在方法中声明有什么不同?

  •  
  •   agzero · 2020-12-30 14:33:09 +08:00 · 1399 次点击
    这是一个创建于 1206 天前的主题,其中的信息可能已经有所发展或是发生改变。

    今天刷 LeetCode 遇到一个很有意思的 trick:

    func reversePrintDefer(head *ListNode) (res []int) {
    	//res := make([]int, 0) 
    	for head != nil {
    		tmp := head
    		defer func() {
    			res = append(res, tmp.Val)
    			fmt.Println(res)
    		}()
    		head = head.Next
    	}
    	return res
    }
    

    如果打开方法中的res,去掉方法的返回值命名,这时候返回的永远是个空切片 无论哪种方式,在 defer 中的打印都能打印出正确值

    有没有大佬知道是什么原因造成的

    2 条回复    2020-12-30 16:18:04 +08:00
    yxcoder
        1
    yxcoder  
       2020-12-30 14:53:51 +08:00   ❤️ 2
    agzero
        2
    agzero  
    OP
       2020-12-30 16:18:04 +08:00
    @yxcoder 多谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2309 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 00:45 · PVG 08:45 · LAX 17:45 · JFK 20:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.