Ask coding questions

← Back to all posts
Rust: how to make a global function that is only callable once?
h
xxpertHacker

My goal is to make this program fail to compile, using only the type system:

pow can be called endlessly, I don't want that.

I tried the following, but it wasn't working without an implementation of the Copy trait:

Since I don't know how to use traits, this failed too:


My real use case is that I have a function which creates a hook that must not be created more than once, and using runtime boolean mutation, checking, and branching could introduce bugs, along with increased code size and unnecessay runtime overhead, where the second call should be prevented at compile-time anyway.


Does anyone know how this could be done?

Answered by 19wintersp [earned 5 cycles]
View Answer
Voters
xxpertHacker
Comments
hotnewtop
19wintersp

Once is the closest thing probably.

xxpertHacker

@19wintersp

This gives

I'm thinking that I'll need static booleans and atomics instead.

19wintersp

@xxpertHacker

gives

¯\_(ツ)_

Coder100

getting singleton vibes here

xxpertHacker

@Coder100 Kind of, like calling the class constructor once, calling this arbitrary function one.

xxpertHacker

@Coder100 So, you have no clue how to do this though?

Coder100

sorry no @xxpertHacker