본문 바로가기
golang

Internal package in golang

by marble25 2023. 9. 3.

Golang을 이용해서 개발하다가 흥미로운 개념을 발견했다.

v1.4부터 추가된 개념으로, internal package라는 개념이다.

공식 홈페이지에 release 노트를 보면 다음과 같이 설명되어 있다.

Internal packages

Go's package system makes it easy to structure programs into components with clean boundaries, but there are only two forms of access: local (unexported) and global (exported). Sometimes one wishes to have components that are not exported, for instance to avoid acquiring clients of interfaces to code that is part of a public repository but not intended for use outside the program to which it belongs.

The Go language does not have the power to enforce this distinction, but as of Go 1.4 the [go](<https://go.dev/cmd/go/>) command introduces a mechanism to define "internal" packages that may not be imported by packages outside the source subtree in which they reside.

To create such a package, place it in a directory named internal or in a subdirectory of a directory named internal. When the go command sees an import of a package with internal in its path, it verifies that the package doing the import is within the tree rooted at the parent of the internal directory. For example, a package .../a/b/c/internal/d/e/f can be imported only by code in the directory tree rooted at .../a/b/c. It cannot be imported by code in .../a/b/g or in any other repository.

For Go 1.4, the internal package mechanism is enforced for the main Go repository; from 1.5 and onward it will be enforced for any repository.

Full details of the mechanism are in the design document.

기존에는 local(export X)와 global(export) 타입의 access만 가능했다. 그러다 누군가 repository 안에서만 사용되고, program 밖에서는 사용되지 못하는 컴포넌트를 원해서 탄생한 개념이라고 한다.

internal 이라는 디렉토리를 만들고 그 안에 패키지를 가지면, internal package를 사용할 수 있다.

  • /a/b/c/internal/d/e/f 의 코드는 /a/b/c 를 루트로 하는 디렉토리 트리의 코드에서만 가져올 수 있다. 만일, /a/b/g 에 작성된 package에서 가져오려고 시도한다면 compile 에러가 발생한다.

golang에서 폴더명을 통해 패키지 노출을 제한한다는 점이 흥미로웠다.

'golang' 카테고리의 다른 글

goroutine 파헤치기  (0) 2023.09.23
Formatting in golang  (0) 2023.09.03
Go 언어를 활용한 분산 서비스 개발  (0) 2023.07.23
실무에 바로 쓰는 Go 언어 핸즈온 가이드  (0) 2023.07.12
[후기] entgo 두달 사용 후기  (0) 2022.07.23