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