[Go] go-tour _ basics [17/17]
ํด๋น๊ธ์ ์๋ ๋ด์ฉ์ ๋ฐํ์ผ๋ก ๊ณต๋ถํ ๋ด์ฉ๋ค์ ์ ๋ฆฌํ ๊ธ ์ ๋๋ค.
Go๋ฅผ ํฅํ ์ฌํ
go-tour-ko.appspot.com
Short variable declarations
package main
import "fmt"
func main() {
var i, j int = 1, 2
k := 3
c, python, java := true, false, "no!"
fmt.Println(i, j, k, c, python, java)
}
ํจ์ ๋ด์๊ฒ๋ := ํ์์ผ๋ก type์ ์ง์ ํด์ฃผ์ง์์๋ ๋ณ์ ์ ์ธ์ด ๊ฐ๋ฅํ์ง๋ง
ํจ์ ๋ฐ์ ๋ณ์๋ฅผ ์ ์ธํ ๊ฒฝ์ฐ์๋ := ํ์์ด ์ฌ์ฉ ๋ถ๊ฐ๋ฅํ๋ค.
Basic types
package main
import (
"fmt"
"math/cmplx"
)
var (
ToBe bool = false
MaxInt uint64 = 1<<64 - 1
z complex128 = cmplx.Sqrt(-5 + 12i)
)
func main() {
fmt.Printf("Type: %T Value: %v\n", ToBe, ToBe)
fmt.Printf("Type: %T Value: %v\n", MaxInt, MaxInt)
fmt.Printf("Type: %T Value: %v\n", z, z)
}
go์ ๊ธฐ๋ณธ์ ์ธ ํ์ ๋ค ์ ๋ฆฌ.
%T : ํด๋น ๊ฐ์ ํ์ ์ ์ถ๋ ฅํ๋ค.
%v : ๋ชจ๋ ๊ฐ์ ๊ธฐ๋ณธ ํ์ ์ง์ ์.
Zero values
package main
import "fmt"
func main() {
var i int
var f float64
var b bool
var s string
fmt.Printf("%v %v %v %q\n", i, f, b, s)
}
- ์ซ์ type์๋ 0
- boolean type์๋ false
- string์๋ "" (๋น ๋ฌธ์์ด)
๊ธฐ๋ณธ์ ์ธ ํด๋น ํ๋ค์ value๋ ์์ ๊ฐ์ ํ์์ผ๋ก ์ด๋ฃจ์ด์ง๊ฒ ๋๋ค.
Type conversions
package main
import (
"fmt"
"math"
)
func main() {
var x, y int = 3, 4
var f float64 = math.Sqrt(float64(x*x + y*y))
var z uint = uint(f)
fmt.Println(x, y, z)
}
go์ ๊ฒฝ์ฐ์๋ C์ ๋ค๋ฅด๊ฒ ๋ค๋ฅธ ํ์ ๋ค ๊ฐ์ ๋ณํ์ด ๋ถ๊ฐ๋ฅํ๋ค๊ณ ํ๋ค.
ex)
c์ธ์ด์ ๊ฒฝ์ฐ
int c = 97์ %c๋ก ์ถ๋ ฅํ๋ฉด a๋ผ๋ ๋ฌธ์๊ฐ ๋์ฌ ์ ์์๋ง go์์๋ ๋ถ๊ฐ๋ฅํ๋ค๋ผ๋ ์ด์ผ๊ธฐ
์ค๋ช ์ํด์ค ์ง์ค๋๋ ๋๋ฌด ๊ณ ๋ง์์! ๐
Type inference
package main
import "fmt"
func main() {
v := 42 // change me!
fmt.Printf("v is of type %T\n", v)
}
:= ํ์์ผ๋ก ๋ช ์์ ์ธ ์ ์ธ์ ํด์ฃผ๋ฉด ํด๋น ๊ฐ์ ๋ฐ๋ผ์ ๋ณ์์ ํ์ ์ ๋ณ๊ฒฝํ ์ ์๋ค.
ํจ์ ๋ด์์๋ง ๊ฐ๋ฅ.
Constants
package main
import "fmt"
const Pi = 3.14
func main() {
const World = "ไธ็"
fmt.Println("Hello", World)
fmt.Println("Happy", Pi, "Day")
const Truth = true
fmt.Println("Go rules?", Truth)
}
๊ฐ์ ๋ฐ๊ฟ ์ ์๋ const๋ฅผ ์ ์ธํ๋ ๋ฐฉ๋ฒ
Numeric Constants
package main
import "fmt"
const (
// Create a huge number by shifting a 1 bit left 100 places.
// In other words, the binary number that is 1 followed by 100 zeroes.
Big = 1 << 100
// Shift it right again 99 places, so we end up with 1<<1, or 2.
Small = Big >> 99
)
func needInt(x int) int { return x*10 + 1 }
func needFloat(x float64) float64 {
return x * 0.1
}
func main() {
fmt.Println(needInt(Small))
fmt.Println(needFloat(Small))
fmt.Println(needFloat(Big))
}
type๊ฐ ์ ํด์ง์ง์์ ์์๊ฐ์ ์ํฉ์ ๋ง์ถฐ์ ๊ทธ ๊ฐ์ด ์ฌ์ฉ๋๋ค.
๋๊ฒ ์ ๋ฐํ๋ค๊ณ ์๊ฐํ๋ ๊ฒ ์์์ ๊ฐ์ ์ํฉ์ ๋ง์ถฐ ์ ๋์ ์ผ๋ก ์ธ ์ ์๋ค๋๊ฒ ํธํ๊ณ
ํ์ฉ์ฑ์ด ๋ง์๊ฑฐ๊ฐ๋ค๊ณ ์๊ฐ์ด ๋ค์๋ค.