How to convert a 4 element &[u8] into i32? [duplicate] - rust

This question already has answers here:
How can I convert a buffer of a slice of bytes (&[u8]) to an integer?
(4 answers)
Closed 1 year ago.
I have an i32 that i pass to my keyvalue database.
let a = 1234i32;
db.put(&a.to_be_bytes());
But i get it back as &[u8], how to convert it back to i32?
update: this example pretty much does what i want.
use std::convert::TryInto;
fn read_be_i32(input: &[u8]) -> i32 {
i32::from_be_bytes(input.try_into().unwrap())
}

Use i32::from_be_bytes and from this answer, TryFrom:
use std::convert::TryFrom;
fn main() {
let a = 1234i32.to_be_bytes();
let a_ref: &[u8] = &a;
let b = i32::from_be_bytes(<[u8; 4]>::try_from(a_ref).expect("Ups, I did it again..."));
println!("{}", b);
}
Playground

Related

How to get a Vec from polars Series or ChunkedArray?

In Rust Polars, how to cast a Series or ChunkedArray to a Vec?
You can collect the values into a Vec.
use polars::prelude::*;
fn main() -> Result<()> {
let s = Series::new("a", 0..10i32);
let as_vec: Vec<Option<i32>> = s.i32()?.into_iter().collect();
// if we are certain we don't have missing values
let as_vec: Vec<i32> = s.i32()?.into_no_null_iter().collect();
Ok(())
}

rust, work around: cannot return value referencing local variable [duplicate]

This question already has answers here:
Return local String as a slice (&str)
(7 answers)
Closed 7 years ago.
Simple code:
fn foo() -> Vec<&'static str> {
let mut vec = Vec::new();
let mut string = String::new();
// doing something with string...
vec.push(string.as_str());
return vector; // error here: string doesn't live long enough
}
I have problem that I need to process with string and return it in Vec as str. Problem is that binding string doesn't live long enough, since it goes out of scope after foo. I am confused and I don't really know how to solve that.
A &'static str is a string literal e.g. let a : &'static str = "hello world". It exists throughout the lifetime of the application.
If you're creating a new String, then that string is not static!
Simply return a vector of String.
fn foo() -> Vec<String> {
let mut vec = Vec::new();
let mut string = String::new();
// doing something with string...
vec.push(string);
return vec;
}
fn main() {
foo();
}

Rust: How to take input from a file and compute it? [duplicate]

This question already has answers here:
How to do simple math with a list of numbers from a file and print out the result in Rust?
(2 answers)
Closed 3 years ago.
I just need to find a way to work with input to do simple maths with it. I've been trying this for a couple of days for the advent of code 2019 day 1
use std::fs::File;
use std::io::{BufRead, BufReader, Error};
fn main() -> Result<(), Error> {
let path = "input.txt";
let input = File::open(path)?;
let buffered = BufReader::new(input);
for line in buffered.lines() {
line.parse::<i32>().unwrap();
line / 2;
println!("{:?}", line);
}
Ok(())
}
If you want your code to compile.
use std::fs::File;
use std::io::{BufRead, BufReader, Error};
fn main() -> Result<(), Error> {
let path = "input.txt";
let input = File::open(path)?;
let buffered = BufReader::new(input);
for line in buffered.lines() {
println!("{:?}", line.unwrap().parse::<i32>().unwrap() / 2);
}
Ok(())
}

What does [..] mean for Rust slices and what is it called? [duplicate]

This question already has answers here:
What does the "two periods" operator mean in the context of a subscript inside of square brackets?
(2 answers)
Closed 3 years ago.
I've found this example in a README:
use std::env;
fn main() {
let filename: &str = &env::args().nth(1).unwrap()[..];
let filename2: &str = &env::args().nth(1).unwrap();
println!("{:?}", filename);
println!("{:?}", filename2)
}
I'm interested in the first line: let filename ....
What does the [..] after the unwrap mean?
The second line let filename2 ... is my own test that both filename and filename2 are the same, or do I miss something?
What is this [..] called?
A string can be used as an array of bytes. This addition does strictly nothing:
#![feature(core_intrinsics)]
fn print_type_of<T>(_: &T) {
println!("{}", unsafe { std::intrinsics::type_name::<T>() });
}
fn main() {
let x = "abc";
print_type_of(&x); // &str
let x = &x[..];
print_type_of(&x); // &str
}
[..] takes the full range, and & takes a reference to it.

Why can a variable be bound to another value even its ownership has moved? [duplicate]

This question already has answers here:
Why does compilation not fail when a member of a moved value is assigned to?
(2 answers)
Closed 6 years ago.
In the following code, the ownership of MyStruct { s: 5u32 } is moved to y by let y = x;, but why does x.s = 6 still work?
struct MyStruct {
s: u32,
}
fn main() {
let mut x = MyStruct { s: 5u32 };
let y = x;
x.s = 6; //why this line does not cause an error?
println!("{}", y.s);
}
I'm pretty sure this is a bug, since adding the line println!("{}", x.s) at the end causes the compiler to complain.

Resources