MOJO: How do I convert StringRef to Int?

from sys import argv

fn fibonacci(n: Int) -> Int:
    if n == 0:
        return 0
    elif n == 1:
        return 1
    return n + fibonacci(n-1)

fn main():
    var vls: StringRef = argv()[0]
    print("vls = ", vls)
    var n: Int = Int(vls)
    var kys: Int = fibonacci(n)

Well, I'm testing out a new language with code provided above. I want to pass the n via cli, however an error appears when I try to explicitly cast the argument:

:!mojo /home/quakumei/Desktop/iamjaf/mytests/mojo-lang/mojo-small/fibonacci.mojo
/home/quakumei/Desktop/iamjaf/mytests/mojo-lang/mojo-small/fibonacci.mojo:13:21: er
ror: cannot construct 'Int' from 'StringRef' value in 'var' initializer
    var n: Int = Int(vls)
mojo: error: failed to parse the provided Mojo

shell returned 1

I've seen information on casting Float to Int and backwards, however didn't see any info on how can I convert StringRef to Int properly. Is there some kind of std::stoi, like in C++?


  • Always try to search the docs first! There you can find the atol function, which will convert a String to an Int.