Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Variables Go中的变量init_Variables_Go_Scope_Initialization - Fatal编程技术网

Variables Go中的变量init

Variables Go中的变量init,variables,go,scope,initialization,Variables,Go,Scope,Initialization,我看到了下面的代码(我简化了一点) 如果我正确理解此代码,则将逐行执行var endpoints.endpoints{…}中的代码,并且endpoints=s.endpoints…行初始化上面声明的var endpoints变量 我认为这样重写是正确的(如果我错了,请纠正我): 有人能解释一下为什么初始化写在var endpoints.endpoints{…}中吗。这样做有什么想法吗?我错过什么了吗 它们是等价的 {…}块与带有var关键字的变量声明无关。它恰好是一个接一个地写的 {…}是一个简

我看到了下面的代码(我简化了一点)

如果我正确理解此代码,则将逐行执行
var endpoints.endpoints{…}
中的代码,并且
endpoints=s.endpoints…
行初始化上面声明的
var endpoints
变量

我认为这样重写是正确的(如果我错了,请纠正我):

有人能解释一下为什么初始化写在
var endpoints.endpoints{…}
中吗。这样做有什么想法吗?我错过什么了吗

它们是等价的

{…}
块与带有
var
关键字的变量声明无关。它恰好是一个接一个地写的

{…}
是一个简单的,没有别的。
var
声明不需要该块,即使有,也与变量声明无关。可以在插入语句的任何位置插入块

使用显式块(当不需要显式块时)的罕见情况是对语句进行分组,并控制变量的范围和其中声明的其他标识符,因为变量的范围结束于最内部包含块()的末尾。

它们是等效的

{…}
块与带有
var
关键字的变量声明无关。它恰好是一个接一个地写的

{…}
是一个简单的,没有别的。
var
声明不需要该块,即使有,也与变量声明无关。可以在插入语句的任何位置插入块


使用显式块(不需要显式块时)的罕见情况是对语句进行分组,并控制变量的范围和其中声明的其他标识符,因为变量的范围结束于最内部包含块()的末尾。

添加新块将创建新的变量范围,在该块中声明的变量在其外部将不可用:

var endpoints s.Endpoints
{
    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints = s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }
}

// service and repository  variables are not defined here!
在您特定的简化示例中,这没有什么意义,但如果您有其他具有相同变量的块,则更有意义。例如:

var endpoints s.Endpoints
{
    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints = s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }
}

 // Get another repository
{
    repository := otherRepo.NewRepository(db)
    repository.DoSomething()
}


有些人认为这是“良好的卫生”。就个人而言,我认为降低可读性是不值得的。

添加一个新块将创建一个新的变量范围,并且在该块中声明的变量在其外部将不可用:

var endpoints s.Endpoints
{
    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints = s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }
}

// service and repository  variables are not defined here!
在您特定的简化示例中,这没有什么意义,但如果您有其他具有相同变量的块,则更有意义。例如:

var endpoints s.Endpoints
{
    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints = s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }
}

 // Get another repository
{
    repository := otherRepo.NewRepository(db)
    repository.DoSomething()
}


有些人认为这是“良好的卫生”。就个人而言,我认为不值得降低可读性。

这样的代码通常是一个很好的指示,您需要将函数一分为二。是的,它通常是@SchwernCode,尽管不一定总是这样,通常是一个很好的指示,您需要将函数一分为二。是的,它通常——尽管不一定总是——是@Schwern