2 years ago
#16111
Gabriel Golfetti
Managing global state from library
I'm writing a library in Rust that implements a certain struct and methods on it. I want, however, to expose to the consumer only the methods and leave the state variables hidden, with just a few exposed through getter functions. As an example of the sort of behavior I want, here's a C snippet:
//library.h
void init();
void do_stuff();
int get();
//library.c
typedef struct State {
int a,b;
} State;
State G_STATE;
void init() {} //Initialize G_STATE
void do_stuff() {} //Logic with G_STATE
int get() { return G_STATE.a; } //Returns only part of G_STATE
//main.c
#include <stdio.h>
#include "library.h"
int main() {
init();
do_stuff();
printf(get());
return 0;
}
This is clearly very unsafe and all that, but it's enough to describe the behavior. Is there an idiomatic Rust way to get this style of API? A way that, perhaps also doesn't have the same shortcomings as the snippet above in terms of memory safety and undefined lifetimes of globals?
rust
state
global
api-design
idioms
0 Answers
Your Answer