티스토리 뷰

반응형

개발을 할 디렉토리를 생성한다.

 

개발을 할 디렉토리를 생성했다면 그 아래에 src, pkg, bin 이름으로 3개의 디렉토리를 생성한다.

  • src: Go 소스 파일
  • pkg: 패키지 파일 (확장자: .a)
  • bin: 실행 파일

 

package main // package 선언

import "fmt" // 외부 패키지 import

func main() {
	fmt.Println("Hello World!")
}

src 폴더 아래에 hello 디렉토리를 생성하고 hello.go이름으로 위의 파일을 생성한다.

 

Go 코드는 패키지 선언으로 시작한다. Go 패키지는 모듈과 라이브러리와 유사하게 코드를 구조화하고 재사용하기 위한 단위이다. main 패키지는 프로그램의 시작점 역할을 한다.

 

Go의 기본 라이브러리인 fmt 패키지를 임포트 했다.

 

main은 Go 프로그램의 시작점이다. Go의 함수를 선언하는 키워드인 func를 사용하여 선언하였다.

 

Go에서는 외부 패키지의 함수를 사용할 때는 패키지명.함수명(매개변수) 형태로 사용한다. fmt.Println를 사용해서 "Hello World"를 출력하고 있다.

 

https://pkg.go.dev/std

 

Standard library - pkg.go.dev

Directories ¶ Expand all tar Package tar implements access to tar archives. Package tar implements access to tar archives. zip Package zip provides support for reading and writing ZIP archives. Package zip provides support for reading and writing ZIP arch

pkg.go.dev

위의 사이트에서 go의 기본라이브러리들을 알 수 있다.

 

https://golang.org/doc/

 

Documentation - The Go Programming Language

Documentation The Go programming language is an open source project to make programmers more productive. Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and netwo

golang.org

go의 공식 문서이다.

 

go run src/hello/hello.go

터미널에 위의 명령어를 입력한다.

 

위의 명령어는 빌드 단계를 거치지 않고 소스 코드를 바로 실행한다.

 

그럼 Hello World가 출력된다.

 

💡 만약 파일이 실행되지 않고 에러가 발생한다면 에디터를 끄고 다시 켜보자

 

go build

위의 명령어는 빌드 후 현재 디렉터리에 실행 파일을 생성한다.

 

💡go build를 입력 했을 때 go: go.mod file not found in current directory or any parent directory; see 'go help modules' 해결법

미널에 아래의 명령어를 입력
go env -w GO111MODULE=auto

 

실행파일이 생성된 모습

 

./실행파일명

./hello를 입력하면 실행파일이 실행된다.

 

 

위에서 bin에 실행파일이 생성된다고 하였는데, go build를 하면 소스코드와 같은 디렉토리 아래에 실행파일이 생성된다.

 

아래의 명령어를 입력하면  %GOPATH%\bin에 실행파일이 생성될  것이다. (GOPATH는 기본적으로 $HOME/go 이고 만약 다른 디렉토리에서 작업하고 있었다면 GOPATH를 변경해주면 된다.)

 

go install

그럼 hello 실행파일이 bin 디렉토리 아래에 생성된 것을 확인할 수 있다.

 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함