github.com/bazelbuild/rules_go@v0.47.2-0.20240515105122-e7ddb9ea474e/docs/go/core/embedding.md (about) 1 ## Embedding 2 3 The sources, dependencies, and data of a `go_library` may be *embedded* 4 within another `go_library`, `go_binary`, or `go_test` using the `embed` 5 attribute. The embedding package will be compiled into a single archive 6 file. The embedded package may still be compiled as a separate target. 7 8 A minimal example of embedding is below. In this example, the command `bazel 9 build :foo_and_bar` will compile `foo.go` and `bar.go` into a single 10 archive. `bazel build :bar` will compile only `bar.go`. Both libraries must 11 have the same `importpath`. 12 13 ``` bzl 14 go_library( 15 name = "foo_and_bar", 16 srcs = ["foo.go"], 17 embed = [":bar"], 18 importpath = "example.com/foo", 19 ) 20 21 go_library( 22 name = "bar", 23 srcs = ["bar.go"], 24 importpath = "example.com/foo", 25 ) 26 ``` 27 28 Embedding is most frequently used for tests and binaries. Go supports two 29 different kinds of tests. *Internal tests* (e.g., `package foo`) are compiled 30 into the same archive as the library under test and can reference unexported 31 definitions in that library. *External tests* (e.g., `package foo_test`) are 32 compiled into separate archives and may depend on exported definitions from the 33 internal test archive. 34 35 In order to compile the internal test archive, we *embed* the `go_library` 36 under test into a `go_test` that contains the test sources. The `go_test` 37 rule can automatically distinguish internal and external test sources, so they 38 can be listed together in `srcs`. The `go_library` under test does not 39 contain test sources. Other `go_binary` and `go_library` targets can depend 40 on it or embed it. 41 42 ``` bzl 43 go_library( 44 name = "foo_lib", 45 srcs = ["foo.go"], 46 importpath = "example.com/foo", 47 ) 48 49 go_binary( 50 name = "foo", 51 embed = [":foo_lib"], 52 ) 53 54 go_test( 55 name = "go_default_test", 56 srcs = [ 57 "foo_external_test.go", 58 "foo_internal_test.go", 59 ], 60 embed = [":foo_lib"], 61 ) 62 ``` 63 64 Embedding may also be used to add extra sources sources to a 65 `go_proto_library`. 66 67 ``` bzl 68 proto_library( 69 name = "foo_proto", 70 srcs = ["foo.proto"], 71 ) 72 73 go_proto_library( 74 name = "foo_go_proto", 75 importpath = "example.com/foo", 76 proto = ":foo_proto", 77 ) 78 79 go_library( 80 name = "foo", 81 srcs = ["extra.go"], 82 embed = [":foo_go_proto"], 83 importpath = "example.com/foo", 84 ) 85 ``` 86