윈도우
리눅스
- Centos : yum install -y golang
- ubuntu : apt-get install -y golang
맥
brew update
brew install go@1.17
go version
wecode/go/helloworld $ go mod init helloworld // <- 프로젝트 초기화 go: creating new go.mod: module helloworld wecode/go/helloworld $ ls -al total 0 drwxrwxrwx 1 sjs sjs 4096 May 10 01:41 . drwxrwxrwx 1 sjs sjs 4096 May 10 01:40 .. -rwxrwxrwx 1 sjs sjs 27 May 10 01:41 go.mod // <- go.mod 파일 생성됨 wecode/go/helloworld $ touch main.go // <- main.go 생성 wecode/go/helloworld $ ls -al -rwxrwxrwx 1 sjs sjs 27 May 10 01:41 go.mod -rwxrwxrwx 1 sjs sjs 0 May 10 2022 main.go wecode/go/helloworld $ // <---- 기본설정 완료
package main // 파일의 패키지 지정 import "fmt" // 외부 패키지 사용 func main() { // 프로그램 시작 fmt.Println("Hello World") }//패키지명. 패키지 함수
import "fmt" // 무조건 fmt만 쓰는이유는? // 기본 패키지에도 프린트 해주는 함수가 있으나 굳이 fmt를 사용 하는 이유는 // 압축? (추후 수정)
접근제어자 : public, private, protected, packaged 등등
방법
Go 언어는 패키지 단위의 점근 제어 밖에 못함
패키지 기준으로 Private(Unexported) 이냐 Public(Exported)이냐 차이
// 파일 생성 wecode/go/helloworld $ mkdir apkg wecode/go/helloworld $ cd apkg wecode/go/helloworld/apkg $ touch pi.go wecode/go/helloworld/apkg $ ls -al total 0 drwxrwxrwx 1 sjs sjs 4096 May 10 01:59 . drwxrwxrwx 1 sjs sjs 4096 May 10 01:59 .. -rwxrwxrwx 1 sjs sjs 0 May 10 01:59 pi.go wecode/go/helloworld/apkg $
wecode/go/helloworld/apkg $ cat pi.go package apkg const pi = 3.141592
vscode 에서 그림과 같이 not exported 발생 wecode/go/helloworld $ go run main.go # command-line-arguments ./main.go:9:14: cannot refer to unexported name apkg.pi ./main.go:9:14: undefined: apkg.pi // main.go 실행에도 실행 불가
## 수정 후 ## package main import ( "fmt" "helloworld/apkg" ) func main() { fmt.Println(apkg.Pi) } ---------------------------------------------- package apkg const Pi = 3.141592 // main.go와 pi.go 모두 pi의 P를 대문자로 수정 후 실행가능 $ go run main.go 3.141592
// main.go package main import ( "fmt" "helloworld/apkg" ) func main() { fmt.Println(apkg.GetNumber()) fmt.Println(apkg.GetNumber()) fmt.Println(apkg.GetNumber()) fmt.Println(apkg.GetNumber()) }
// get_number.go package apkg var number = 0 func GetNumber() int { number++ return number }
// 결과 1 2 3 4
다중 반환
이름이 있는 반환값
// 정수형
Signed
int8 - 1byte
int16 - 2byte
int32 - 4byte
int64 - 8byte
int - WORDUnsigned
uint8 - 1byte
uint16 - 2byte
uint32 - 4byte
uint64 - 8byte
uint - WORD별칭
byte - uint8
rune - int32, unicode point
답 : -1
답 : 65535
관련 자료 : https://stackoverflow.com/a/38660373
부동소수점
float32 - 4byte float64 - 8byte
부동 소수점 사용시 정확한 숫자가 나오지 않는다
예 : 1.0000000001