Backend with Golang

[Go] 재선언과 재할당

아직개구리 2023. 11. 11. 14:39

Redeclaration and reassignment 

 

In a := declaration a variable v may appear even if it has already been declared, provided:

  • this declaration is in the same scope as the existing declaration of v (if v is already declared in an outer scope, the declaration will create a new variable §),
  • the corresponding value in the initialization is assignable to v, and
  • there is at least one other variable that is created by the declaration. 

이전 것이 이미 선언되어있는데 다시 :=를 통해서 v에 값을 재 할당 하는 경우는 이전 v와 같은 스코프 안에 있고, assign할 수 있는 value 이며, 최소 하나의 다른 variable은 declaration에 의해 생성될 때 사용가능하다. 

 

이때 헷갈렸던 부분은 만약 바깥 스코프에서 f, err := function() 이렇게 err가 선언되어 있을 때 for loop 안쪽에서 새로 v, err:= function() 이렇게 선언하게 되면 err는 바깥의 scope의 err에 재할당 되는지 궁금했는데, effective go에서 f가 밖에서 선언되었다면 안쪽에선 새로운 variable이 생성된다는 것을 명시해 놓아서 정확하게 알 수 있었다.