Go 기초
Go Variables and Constants: var, := and const
Two ways to declare a variable, what a zero value is, and values that never change.
배울 내용
- var and :=
- Zero values
- const
Declaration → result
var year int0, the zero valuescore := 10int, inferredconst MaxScore = 100cannot changeDeclare, then use
Go has two ways to create a variable. var names the type, and := lets Go work out the type from the value. A variable that is declared without a value gets a zero value such as 0 or an empty string.
year is declared without a value, so it starts at 0 until 2009 is assigned. := can only be used inside a function and can declare several variables at once. A const cannot be changed after it is declared.
핵심 포인트
- var names the type; := infers it.
- A variable without a value starts at its zero value.
- A const cannot change.
실행 가능한 Go 예제
Go
main.go
package main
import "fmt"
const MaxScore = 100
func main() {
var language string = "Go"
var year int // zero value: 0
score := 10 // short declaration, type inferred
score += 5
year = 2009
name, version := "gopher", 1.21
fmt.Println(language, year, score, MaxScore)
fmt.Println(name, version)
}
Go 2009 15 100
gopher 1.21연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- Swap First and Last Exchange the first and last items of a list. 쉬움
- Running Sum Replace each value with the total so far. 쉬움