Get kubernetes namespace into variable using kube rust?

I'm able to get kubernetes namespace using kube - Rust but it prints the output into stdout.

#[tokio::main]
pub async fn get_namespace() {
    let client = Client::try_default().await.unwrap();
    let namespace: Api<Namespace> = Api::all(client);
    let s1 = namespace.list(&ListParams::default())
    .await
    .unwrap()
    .items
    .iter()
    .map(|name| name.name())
    .for_each(|name| println!("{}",name)); 

    println!("s1 :{:?}",s1); // shows only ()
}

How can i assign the output to any variable? for eg s1?

Your code is going over each of the items and printing the name. You can just collect the names into a new Vec instead.

#[tokio::main]
pub async fn get_namespace() {
    let client = Client::try_default().await.unwrap();
    let namespace: Api<Namespace> = Api::all(client);
    let names: Vec<String> = namespace
        .list(&ListParams::default())
        .await
        .unwrap()
        .items
        .iter()
        .map(|name| name.name().to_string())
        .collect();

    println!("s1 :{:?}", names);
}

I had to guess a bit about the types involved since it looks like that Namespace type may not be coming from kube but hopefully that gets you on the right track

Thank you @semicoleon above code worked and i was able to get the output as

s1 :["default", "kube-system", "kube-public", "kube-node-lease", "test", "test1"]

I also tried below code using for loop. It's also working.

        // print default namespace
        for n1 in namespace.list(&ListParams::default()).await.unwrap() {
            if current_namespace == n1.name() {
                println!("{}", n1.name().green());
            } else {
                println!("{}", n1.name());
            }
        }

No, it does not. That code only prints the namespaces.

@moy2010 yes, it only prints the namespace.
Sorry i was not clear in the first question. I just needed a way to get those values into any variable and then run for loop to compare with current_namespace.

Here is the code implementation kn added for namespace switch · koolwithk/kx-kn-rust@29940b5 · GitHub
I'm just learning rust so code is not well written.

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.