下面的代码失败。
fn greet(n: Bool) -> String:
return "Hello, 2!"
fn greet(name: String) -> String:
return "Hello, " + name + "!"
fn main():
print(greet("hi"))
print(greet(False))
首先欢迎来到Mojo🔥!
你们真的很亲近。我看到两个问题:
Bool
版本的greet()
未使用arg,这将导致编译器变得挑剔。因此,在下面的示例中,我添加了 n
的评估,只是为了快速跳过这个问题。greet("hi")
是传递 StringLiteral
而不是 String
。通过在 str()
周围使用 "hi"
,您可以将其转换为 String
。# file __temp/overload.mojo
fn greet(n: Bool) -> String:
if n:
return "Hello! 'n' was True!"
else:
return "Heya! 'n' was False!"
fn greet(name: String) -> String:
return "Hello, " + name + "!"
fn main():
print(greet(str("world")))
print(greet(False))
结果:
Hello, world!
Heya! 'n' was False!
此外,您可以使用
String
特征,而不用担心 StringLiteral
与 Stringable
。它标识提供 __str__()
方法的任何对象(包括您自己的自定义混合物)。
# updated file contents
fn greet(n: Bool) -> String:
if n:
return "Hello! 'n' was True!"
else:
return "Heya! 'n' was False!"
fn greet[T: Stringable](name: T) -> String:
return "Hello, " + str(name) + "!"
@value # this makes it so I don't have to build the init, copy, move, and other basic lifetime stuff
struct MyStruct(Stringable):
var some_data: Int
var more_data: Bool
fn __str__(self) -> String:
return "Call me Bob, even though I'm really this: 'MyStruct(" + str(self.some_data) + ", " + str(self.more_data) + ")'"
fn main():
print(greet("world"))
print(greet(False))
var x = MyStruct(5, True)
print(greet(x))
结果:
Hello, world!
Heya! 'n' was False!
Hello, Call me Bob, even though I'm really this: 'MyStruct(5, True)'!
在这里阅读更多关于
Stringable
的信息:
https://docs.modular.com/mojo/manual/traits#the-intable-and-stringable-traits
值得注意的是:此答案是 Mojo nightly 版本 2024.5.1515 (077049dc) 的最新答案。该语言仍在不断发展;这篇文章和任何未来的读者之间可能会发生微妙的变化。