Return a struct from a function

Rust

examples/functions/return-struct/Cargo.toml

[package]
name = "return-struct"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0.200", features = ["derive"] }
serde_json = "1.0.116"

examples/functions/return-struct/data.json

{
    "name": "J. Son",
    "number": 67
}

examples/functions/return-struct/data.txt

Hello World,23

examples/functions/return-struct/src/main.rs

use serde::Deserialize;

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
struct Thing {
    name: String,
    number: u32,
}


#[allow(dead_code)]
#[derive(Debug, Deserialize)]
struct Xhing<'a> {
    name: &'a str,
    number: u32,
}


fn main() {
    let thing = get_thing("Foo Bar");
    println!("{thing:#?}");


    let thing = get_thing_from_text_file("data.txt");
    println!("{thing:#?}");

    let thing = get_thing_from_json_file("data.json");
    println!("{thing:#?}");

    // let thing = get_xhing_from_json_file("data.json");
    // println!("{thing:#?}");

}


fn get_thing(name: &str) -> Thing {
    let thing = Thing {
        name: String::from(name),
        number: 42,
    };
    println!("{thing:#?}");

    thing
}

fn get_thing_from_text_file(path: &str) -> Thing {
    let raw = std::fs::read_to_string(path).unwrap();
    let (name, number) = raw.split_once(",").unwrap();
    Thing {
        name: name.to_string(),
        number: number.parse().unwrap(),
    }

}

fn get_thing_from_json_file(path: &str) -> Thing {
    let raw = std::fs::read_to_string(path).unwrap();
    serde_json::from_str::<Thing>(&raw).unwrap()
}


// fn get_xhing_from_json_file(path: &str) -> Xhing {
//     let raw = std::fs::read_to_string(path).unwrap();
//     serde_json::from_str::<Xhing>(&raw).unwrap()
// }

// fn return_str<'a>() -> &'a str {
//     "abc"   
// }

examples/return-struct/src/main.rs


#[derive(Debug)]
struct Animal<'a> {
    name: String,
    sound: &'a str,
}


fn main() {
    let cat = get_cat();

    println!("Animal: {:?}", cat);
    println!("name: {}", cat.name);
}

fn get_cat() -> Animal {
    let cat = Animal {
        name: String::from("Ketzele"),
        sound: "miau",
    };
    cat
}

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo