#How can I convert String to StringLiteral

4 messages · Page 1 of 1 (latest)

rancid sandal
#

I understood that str() is required to convert things to String like (StringLiteral, Int, Bool, ...), but is there a way to covert String to LiteralString.

As part of learning Mojolang I'm trying the below code, then this conversion issue poped up.

from collections import List
from sys.ffi import external_call

alias system = external_call["system", Int, StringLiteral] 

fn run_commands(arg0: String, args: List[String]) -> Int:
    var command: String = arg0
    for arg in args:
        command += " " + arg[]
    return system(command) # invalid indirect call: argument #0 cannot be converted from 'String' to 'StringLiteral'

fn system2(arg0: String, args: List[String]) -> Int:
    var command: String = arg0
    for arg in args:
        command += " " + arg[]  # Access the element inside the list
    return external_call["system", Int, String](command) 

fn main():
    # var args = List[String]("kill", "-9", "$(lsof -t -i :8000)")
    var args = List[String]("ls")
    _ = run_commands(args[0], args[1:])
    _ = system2(args[0], args[1:])
dusky kernelBOT
#

To help others find answers, you can mark your question as solved via Right click solution message -> Apps -> ✅ Mark Solution

merry basalt
#

StringLiteral is a type which literally means "string typed directly into the file". There is no way to turn a string into a string literal. It's used in places like ORMs to make anything that could produce SQL injection a type error.

tidal yew
#

I’m brand new to Mojo myself, would it work to make the 3rd type of the alias be String not StringLiteral?

This way you can convert StringLiteral to String where/if needed. I’m running into these kind of issues learning the language myself, so I appreciate that you’re sharing @rancid sandal