DEV Community

El Bruno for Microsoft Azure

Posted on β€’ Originally published at elbruno.com on

1

#Rust πŸ¦€ – How to find a variable data type πŸ€”

Hi !

Quick post today to share how to find a variable data type in Rust. As far as I understand, we can use several ways to do this. In example, we can use these 2 std functions:


    use std::any::type_name function
    use std::intrinsics::type_name

Enter fullscreen mode Exit fullscreen mode

The full sample code below create 2 vectors with different data, and print the data type of the vector, and of some of the vector’ elements. This is the output:


   Compiling datatype01 v0.1.0 (C:\src\labs\RustLabs\datatype01)
    Finished dev [unoptimized + debuginfo] target(s) in 0.55s
     Running `target\debug\datatype01.exe`
alloc::vec::Vec<char>
char
i32

Enter fullscreen mode Exit fullscreen mode

Sample Source Code

/*
Copyright (c) 2023
Author : Bruno Capuano
Create Time : 2023 Feb
Change Log :
- Demo to find variables data type
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
fn main() {
let v_char = vec!['A','c','e'];
let v_num = vec![1,2];
print_variable_type(&v_char);
print_variable_type(&v_char[0]);
print_variable_type(&v_num[0]);
}
fn print_variable_type<K>(_: &K) {
println!("{}", std::any::type_name::<K>())
}
view raw rustfinddatatype.rs hosted with ❀ by GitHub



Happy coding!

Greetings

El Bruno

More posts in my blog ElBruno.com.


Top comments (1)

Collapse
 
nazaroni profile image
Nazar β€’

It's so simple... but so usefull.

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more