Monday, April 18, 2022

Go vs Rust - Control Flow

 1 If Expressions

In Rust, the if expression is different Go and other languages.

  • the boolean condition doesn't need to be surrounded by parentheses.
  • if-else conditionals are expressions, and, all branches must return the same type.
let number = if condition { 5 } else { 6 };
or
    let letter: Option<i32> = None;
    if let Some(i) = letter {
        println!("Matched {:?}!", i);
    } else {
        // Destructure failed. Change to the failure case.
        println!("Didn't match a number. Let's go with a letter!");
    }

2 Repetition with Loops

As simple for loop

Go

for i := 0; i < =4; i++{
      fmt.Printf("GeeksforGeeks\n")  
}

Rust
  for x in 0..=10 {
    println!("value of iterator is: {}", x);
  }

For loop as Infinite Loop

Go
for {
      fmt.Printf("GeeksforGeeks\n")  
}

Rust
let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
};

for loop as while Loop

Go
for i < 3 {
    i += 2
}

Rust
while i < 3 {
    i += 2;
}
or
    // Make `optional` of type `Option<i32>`
    let mut optional = Some(0);

    // This reads: "while `let` destructures `optional` into
    // `Some(i)`, evaluate the block (`{}`). Else `break`.
    while let Some(i) = optional {
        if i > 9 {
            println!("Greater than 9, quit!");
            optional = None;
        } else {
            println!("`i` is `{:?}`. Try again.", i);
            optional = Some(i + 1);
        }
    }

Simple range in for loop

Go
     // Here rvariable is a array
    rvariable:= []string{"GFG", "Geeks", "GeeksforGeeks"} 
      
    // i and j stores the value of rvariable
    // i store index number of individual string and
    // j store individual string of the given array
    for i, j:= range rvariable {
       fmt.Println(i, j) 
    }

Rust
    let a = [10, 20, 30, 40, 50];

    for element in a {
        println!("the value is: {}", element);
    }
or
    for number in (1..4).rev() {
        println!("{}!", number);
    }

Using for loop for strings

Go
    for i, j:= range "XabCd" {
       fmt.Printf("The index number of %U is %d\n", j, i) 
    }

Rust
for (i, c) in my_str.chars().enumerate() {
    // do something with character `c` and index `i`
}

For Maps

Go
    mmap := map[int]string{
        22:"Geeks",
        33:"GFG",
        44:"GeeksforGeeks",
    }
    for key, value:= range mmap {
       fmt.Println(key, value) 
    }

Rust
for (k, x) in &mymap {
    println!("Key={key}, Value={val}", key=k, val=x);
}

For Channel

    chnl := make(chan int)
    go func(){
        chnl <- 100
        chnl <- 1000
       chnl <- 10000
       chnl <- 100000
       close(chnl)
    }()
    for i:= range chnl {
       fmt.Println(i) 
    }

Go
  • Go contains only a single loop that is for-loop.
  • Parentheses are not used around the three statements of a for loop.
  • The curly braces are mandatory in for loop.
  • The opening brace should be in the same line in which post statement exists.
  • If the array, string, slice, or map is empty, then for loop does not give an error and continue its flow. Or in other words, if the array, string, slice, or map is nil then the number of iterations of the for loop is zero.








No comments:

Post a Comment