Return value type spec for IO.puts

If you have a function that ends with IO.puts, do you prefer the type spec to state it returns :ok or simply void if all it’s doing is printing to the standard output?

@spec say_hello :: :ok
def say_hello do
 IO.puts "Hello, world"
end

OR

@spec say_hello :: :void
def say_hello do
 IO.puts "Hello, world"
end
2 Likes

IO.puts always returns :ok so your second spec will be wrong. Preference is not relevant here.

btw why :void? This is not C or C++, that wouldn’t be a specially treated value, it would be just a random atom.

2 Likes

I asked ChatGPT first, I know not to take it’s word as gospel, and it stated:

say_hello/0 function takes no arguments and returns the :ok atom. However, this does not accurately reflect the behavior of the function, which simply prints the string “Hello, world” to the standard output and does not return a value.

It is generally a good idea to specify the return type of a function in a type spec, even if the function does not return a value.In Elixir, the :void type is used to indicate that a function does not return a value. It is recommended to use the :void type in the type spec of a function that does not return a value, as it accurately reflects the behavior of the function.

I wasn’t satisfied with its answer when I kept prodding, so I came here. I think your answers right though so thanks for the help!

This error to me indicates that you have void instead of :void. Can you copy and paste the exact code you currently have?

Just a typo😅 It is void, not :void. Thanks for looking though👍

1 Like