在 Elixir 的函数规范中指定类型

specify a type in the function specification in Elixir

如果可以是任何可以转换为字符串的类型,如何在函数规范中指定类型?

@spec push(queue :: %MyQueue{}, data :: ??) :: {}

如果 "can be converted to a string" 是指 to_string/1 函数,它适用于任何实现了 String.Chars 协议的类型,您可以使用类型 String.Chars.t

@spec push(queue :: %MyQueue{}, data :: String.Chars.t) :: {}

IO 模块中的许多函数在其规范中使用此类型,例如IO.write/2.