개인공부/language

[GO] 로컬 패키지 호출 방법

파뱁 2024. 11. 19. 18:49
728x90

지난번 포스팅에는 로컬에 패키지를 만드는 법을 알아보았다.

이번엔 로컬에 만들어둔 패키지를 다른 패키지에서 어떻게 호출해서 사용하는지 확인 해볼 예정이다.

 

우선 두 개의 패키지가 필요하다.

-root
  |- hello
  |- greetings

 

이중에서 greetings는 호출 당할 패키지, hello는 greetings를 호출할 패키지 이다.

 

우선 greetings 패키지 안에 greetings.go를 만든다.

코드는 다음과 같다.

 

package greetings

import "fmt"

func Hello(name string) string {
	message := fmt.Sprintf("Hi, %v. Welcome!", name)
	return message
}

 

다음으로 hello 패키지를 만들고 초기화 한 다음

해당 디렉토리 하위에 hello.go를 만들고 다음과 같이 작성한다.

 

package main

import (
    "fmt"

    "example.com/greetings"
)

func main() {
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

 

위 코드에서 알수 있듯이 우선 print 를 위한 fmt 패키지를 import 하고 

그 다음으로 로컬에 미리 만들어둔 greetings를 import 한다.

 

이렇게만 치면 코드에 빨간 줄이 뜰텐데, 이는 greetings이 아직 인식이 안되기 때문이다.

로컬에서 만든 패키지를 가져오려면 로컬의 패키지 주소를 'example.com/greetings' 로 지정하는 작업이 필요한데,

이는 다음과 같이 진행한다.

 

$ go mod edit -replace example.com/greetings=../greetings

 

위 명령어를 입력한 이후에 hello/go.mod에 들어가보면 다음과 같이 추가 되어있는 것을 확인 할 수 있다.

 

module example/hello

go 1.23.2

replace example.com/greetings => ../greetings

 

example.com/greetings 패키지를 로컬에 위치해 있는 greetings라는 패키지로 지정 하는 작업이다.

 

replace작업이 종료 되었다면 go mod tidy를 통해 해당 패키지를 코드에서 import 해서 사용할 수 있도록

go.mod파일에 추가해주는 작업을 진행한다.

 

해당 작업 까지 완료 되면 최종적으로 hello/go.mod 파일은 다음과 같은 내용을 담고 있다.

 

module example/hello

go 1.23.2

require example.com/greetings v0.0.0-00010101000000-000000000000

replace example.com/greetings => ../greetings

 

위 내용에서 보이는 'require example.com/greetings v0.0.0-00010101000000-000000000000'는 

우리가 로컬에서 작성했던 greetings 패키지가 정상적으로 모듈에 추가 되었음을 알려준다.

 

뒤에 붙은 숫자는 버전 정보로, 별도로 버전을 명시 하지 않았을 경우에는 수도(pseudo) 버전 번호을 붙여 보여진다.

 

만약 별도의 버전 정보를 명시하고자 한다면 다음과 같은 방법으로 진행할 수 있다.

https://go.dev/doc/modules/version-numbers

 

Module version numbering - The Go Programming Language

Module version numbering A module’s developer uses each part of a module’s version number to signal the version’s stability and backward compatibility. For each new release, a module’s release version number specifically reflects the nature of the

go.dev

 

이렇게 패키지의 import 가 정상적으로 완료 된다면 go run . 을 통해 파일을 실행시키면 다음과 같은 결과를 받을수 있다.

 

$ go run .
Hi, Gladys. Welcome!
728x90
반응형

'개인공부 > language' 카테고리의 다른 글

[GO] 배열 선언하기  (0) 2024.12.04
[GO] 에러 핸들링 방법  (1) 2024.11.25
[GO] 함수 기본 작성법  (2) 2024.11.12
[GO] 모듈과 패키지  (0) 2024.11.05
[JAVA] ArrayList가 비어있는지 확인 하기  (0) 2024.02.27