如何在Mojo中为fn函数指定返回类型

huangapple go评论119阅读模式
英文:

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))

huangapple
  • 本文由 发表于 2023年5月28日 14:29:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76350229.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定