🐹 Go 치트시트
Google이 개발한 간결하고 효율적인 언어
기본 문법
변수 선언
var name string = "Go"
var age int = 25
isActive := true
count := 10
조건문
if condition {
statement
} else if otherCondition {
otherStatement
} else {
defaultStatement
}
반복문
for i := 0; i < 10; i++ {
fmt.Println(i)
}
for _, item := range items {
fmt.Println(item)
}
함수 정의
func add(a int, b int) int {
return a + b
}
func greet(name string) {
fmt.Printf("Hello, %s!
", name)
}
구조체와 인터페이스
구조체
type Person struct {
Name string
Age int
Email string
}
person := Person{
Name: "Alice",
Age: 30,
Email: "alice@example.com",
}
메서드
func (p Person) Greet() string {
return fmt.Sprintf("Hello, I'm %s", p.Name)
}
func (p *Person) SetAge(age int) {
p.Age = age
}
인터페이스
type Drawable interface {
Draw()
}
type Circle struct {
Radius float64
}
func (c Circle) Draw() {
fmt.Println("Drawing a circle")
}
빈 인터페이스
func printAnything(value interface{}) {
fmt.Printf("Value: %v
", value)
}
고루틴과 채널
고루틴
go func() {
fmt.Println("This runs in a goroutine")
}()
time.Sleep(1 * time.Second)
채널
ch := make(chan string)
go func() {
ch <- "Hello from goroutine"
}()
message := <-ch
fmt.Println(message)
버퍼드 채널
ch := make(chan int, 3)
ch <- 1
ch <- 2
ch <- 3
fmt.Println(<-ch) // 1
fmt.Println(<-ch) // 2
채널과 range
ch := make(chan int)
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
}()
for value := range ch {
fmt.Println(value)
}