< All Blog

Tuple with a Single Value in Rust

November 11, 2022

In Rust, tuples can be used to have different types of values as a container. Array does not allow you to have different types of elements instead.

When Tuple is useful

For example, overflowing_add returns a tuple with two values, (result, overflowed), where the result is the wrapping version of the result that mathmatic operation returns and overflowed is the boolean whethere that operation caused overflow or not.

let (result, overflowed) = 1_u8.overflowing_add(255_u8);
result.0; //=> 0 (uint8)
result.1; //=> true (boolean)

Tuple with a single value

The interesting story is that, actually Rust allows you to have a tuple with a single value. For example, mytuple in the following source code is a tuple having only single String value, that can be accessed as mytuple.0.

let mytuple = ("hello, world",);
mytuple.0; //=> "hello, world" (String)

Please note that the , (comma) after the value is required to tell compilers that this is a tuple, not parenthetic expression.

Recommended Posts

  1. How to Initialize Vector in Rust

    November 12, 2022
    In Rust, there are a couple of ways to initialize Vector. Vec::new() Vec::new() returns an empty vector. You can initialize a new empty vector and then pushing…
  2. Wrapping Integers in Rust

    November 10, 2022
    In Rust, integers can be wrapped to avoid panicking during runtime. Checking operations Let's think the following example. The following source code panicks, b…