How to get a value from a String Vector?

Hello! I am getting an error on line 9 (zipcode = args[1];). What am I doing wrong?

I've tried doing zipcode = &args[1]; as well, neither work. Please help! Thank you!

use std::io::{self, Write};
use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut zipcode = String::new();

    if args.len() >= 2 {
        zipcode = args[1];
    } else {
        print!("Please enter a zip code to use: ");

        match io::stdin().read_line(&mut zipcode) {
            Ok(_) => {}
            Err(error) => println!("error: {}", error),

    println!("The zipcode is {}", zipcode);


Hi @kotrunga!

So Rust is complaining because you are trying to move the argument out of the vector by doing the assignment zipcode = args[1] and it does not allow you to move out of the vector using indexing syntax. It also doesn't work when you try to use a reference because you said above that zipcode is an owned String, not a reference to a String.

You have two options to fix this. You can clone the string out of args so that you don't move it out. This leaves the original string inside of args:

zipcode = args[1].clone();

Or you could also take the zipcode out out args by using remove()

zipcode = args.remove(1); // Note that you must make `args` mutable now

This will modify the args variable, which may or may not be desirable depending on your use-case.


What a perfect answer. Thanks for explaining the basics to me!

I really appreciate it.

1 Like

Awesome! Glad I could help! :smiley:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.