Go/Blockchain
[Nomad Coin] Tour of Go - #3.2 functions
Gopythor
2022. 7. 10. 19:37
728x90
반응형
- 함수만들기는 func와 함수의 이름만 써주면 끝이다.
package main
func plus(a int, b int){
return a + b
}
func main(){
plus(2, 2)
}
- 두 개의 argument(a int, b int)를 가진 함수를 만들어보자.
- main 함수에 plus(2, 2)를 사용해보자.
- plus 함수에 return a+b를 쓰지만, 이 함수는 return 값을 예상하고 있지 않다.
package main
import "fmt"
func plus(a int, b int) int{
return a + b
}
func main(){
result := plus(2, 2)
fmt.Print(result)
}
- plus 함수의 argument 오른쪽에 retrun type int를 입력한다.
- argument의 type이 같다면 (a, b int) 로도 작성 가능
- 함수는 여러 개의 retrun 값을 가질 수 있다.
package main
import "fmt"
func plus(a int, b int, name string) (int, string){
return a + b, name
}
func main(){
result, name := plus(2, 2, "nico")
fmt.Print(result, name)
}
- plus함수는 a+b의 결과를 return 하고 name도 return 한다.
- 함수에서 argument의 type을 명시하는 것과 다수의 value를 return 할 수 있다는 것이 제일 흥미롭다.
package main
import "fmt"
func plus(a ...int) int{
var total int // total := 0도 가능
for _, item := range a {
total += item
}
return total
}
func main(){
result, name := plus(2, 3, 4, 5, 6, 7, 8, 9, 10)
fmt.Print(result, name)
}
- 함수에 많은 argument를 보낸다.
- 최종 결과가 나올 때 까지 argument를 전부 더한다.
- a는 int의 array가 된다.
- range는 반복가능한 것들을(iterable) 반복(iterate/loop)하게 해줌
- Javascript의 forEach나, python의 for in 같은 것이다.
- index는 0, 1, 2, 3, 4, 5, 6, 7, 8같은 거고 item은 2, 3, 4, 5, 6, 7, 8, 9, 10이다.
- index가 필요없으니 underscore(_)를 쓰면 compiler가 무시한다.
- 모든 argument의 숫자들을 더해서 하나의 결과를 얻을 것이다.
- total 변수를 만들기만 하고 값을 설정하지는 않았다.
- total := 0도 사용 가능하다.
package main
import "fmt"
func main(){
name := "Nicolas!!!! is my name"
for index, letter := range name{
fmt.Println(index, letter)
}
for _, letter := range name{
fmt.Println(string(letter))
}
for _, letter := range name{
fmt.Printf("%o",letter)
}
for _, letter := range name{
fmt.Printf("%b",letter)
}
}
- 실행시 letter가 아니라 byte가 출력된다.
- 이 문제를 해결하려면 formatting에 대해서 배워야 한다.
- Go에서는 number, string, byte를 format할 수 있다.
- 어렵지 않지만, directive를 배워야 한다.
- Index는 정상적으로 출력 됐다(0, 1, 2 ...)
- 각 글자의 byte만을 보여준다(78, 105, 99, 111 ...)
- 고치기 위해서는 string으로 감싸줘야한다.
- print할 때 format도 할 수 있다.
- 이 letter를 octal notation(%o)을 통해서 보도록 format할 수 있다.
- 아니면 binary(%b)로 format해보자
- 다른 방식으로 data를 변환할 수 있다.
- data를 다른 방식으로 encoding할 수 있는 아주 유용한 기능이다.
- digit(%d)를 쓰면 digit이 되고, hexadecimal(%x)를 쓸 수도 있다.
강의 출처 : 노마드코더(https://nomadcoders.co)
728x90
반응형