doudeng9425 2018-02-08 07:50
浏览 100
已采纳

命名返回值和普通返回值有什么区别?

My question is about the different named return value vs normal return value.

my code

package main

import "fmt"

func main() {
    f := fmt.Println
    f(a())
    f(b())
}

func a() int {
    i := 0
    defer func() {
        i += 1
        fmt.Println("a defer : ", i)
    }()

    return i
}

func b() (i int) {
    i = 0

    defer func() {
        i += 1
        fmt.Println("b defer : ", i)
    }()
    return i
}

the result:

the a function return 0

the b function reutrn 1

Why?

  • 写回答

3条回答 默认 最新

  • dongtan6695 2018-02-08 08:12
    关注

    The named return value also allocates a variable for the scope of your function.

    func a() int: While you already return the value of i = 0, but since no named values was defined the static value got returned. So even though you're increasing i in the deferred function it doesn't affect the returned value.

    func b() (i int): The variable i is allocated (and already initialized to 0). Even though the deferred function runs after the i = 0 was returned the scope is still accessible and thus still can be changed.


    Another point of view: you can still change named return values in deferred functions, but cannot change regular return values.

    This especially holds true in the following example:

    func c() (i int) {
        defer func() {
            i = 1
            fmt.Println("c defer : ", i)
        }()
        return 0
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源