This example, mostly stolen adapted from arranfrance.com, shows how to easily call into some go code from Rust.
Disclaimer: I have not used this in production, and would advise cautiosly reviewing ABI guarantees and threading considerations before doing so. For toy programs, and fun stuff such as solving half of an Advent-of-Code day in a second language, it seems to work without issues.
Main actors:
main.go
: Your Go code, with at least one exported CGo function. You can also import other go library as you wish.build.rs
: A script telling cargo to invoke the go compiler, with an argument to build a static library instead of an executable program, and tell cargo to add that static library during linking.main.rs
: Your Rust code, usingstd::ffi
to call to the exported CGo functions.
Usage:
cargo run
That's all there is to it! 🎉
Example output:
➜ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/using_go_from_rust`
Hello from Go. I got the input: This is a test string
Result from Go: 123
Happy hacking!