英文:
How do I specify the return type for fn functions in Mojo
问题
我在运行计算Mojo中阶乘的代码:
fn fact(x:Int):
var mul:Int=1
for i in range(1,x+1):
mul = mul*i
return mul
print(fact(7))
但运行时出现错误:无法将'Int'值隐式转换为'None'的返回值
return mul
我尝试使用fn:Int,但那不是正确的语法。
英文:
I am running a piece of code that calculates the factorial in Mojo:
fn fact(x:Int):
var mul:Int=1
for i in range(1,x+1):
mul = mul*i
return mul
print(fact(7))
But when I run this, I get the error: cannot implicitly convert 'Int' value to 'None' in return value
return mul
I tried using fn:Int, but that's not the correct syntax
答案1
得分: 6
在Mojo中,函数的返回类型是在冒号(:)后面指定的,跟在函数的参数列表后面。要在你的代码中为fact函数指定返回类型,你可以使用->运算符,然后跟上所需的返回类型。
检查这个:
fn fact(x: Int) -> Int:
var mul: Int = 1
for i in range(1, x + 1):
mul = mul * i
return mul
print(fact(7))
英文:
In Mojo, the return type of a function is specified after the colon (:) following the function's parameter list. To specify the return type for the fact function in your code, you can use the -> operator followed by the desired return type.
Check this :
fn fact(x: Int) -> Int:
var mul: Int = 1
for i in range(1, x + 1):
mul = mul * i
return mul
print(fact(7))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论