This project demonstrates how to call Rust functions from Go using FFI (Foreign Function Interface).
- Go 1.16 or later
- Rust and Cargo
- A C compiler (gcc or clang)
Initialize the Rust Project and Generate Header File
cargo new rust_ffi --lib
cd rust_ffi
cbindgen --config cbindgen.toml --output src/rust_ffi.h- First, build the Rust library:
cd rust_ffi
cargo build --release-
Copy the DLL file
rust_ffi.dllto wheremain.gois. -
Then, run the Go program:
go run main.gorust_ffi/- Rust library containing the FFI functionsmain.go- Go program that calls the Rust functions
The Rust library exposes the following functions:
add(a: i32, b: i32) -> i32: Adds two integersmultiply(a: i32, b: i32) -> i32: Multiplies two integersgreet(name: *const u8, name_len: usize) -> *mut u8: Returns a greeting stringfree_string(s: *mut u8): Frees memory allocated by Rust