Tumgik
#main.re
condensedmatters · 1 year
Text
Rust is wonderful, actually
When I first learned about the Rust programming language, I hated it—I was stuck in the mindset that C was perfect and that Rust was for annoying people (because rustaceans can be really annoying tbh). Now that I've started learning Rust, I get it—I fucking get it.
Rust might be one of the nicest programming languages I've ever used. Even outside of all the wonderful language features, just the compiler alone is wonderful. If I get something wrong—unlike in Julia, my favorite programming language—it doesn't dump you with a billion long, incomprehensible stack traces—Rust just pats you on the head, shows you where you went wrong, and goes "if you need more explanation just let me know :))". This goddamn compiler is two steps removed from giving me a blanket and a blowjob.
Like look at this super simple program:
fn main() { println!("hello everynyan!"); }
If I try to break it by throwing in something stupid
fn main() { println!("hello everynyan!"); asdf }
the compiler gives me this error message
error[E0425]: cannot find value 'asdf' in this scope --> main.rs:3:5 | 3 | asdf; | ^^^^ not found in this scope
error: aborting due to previous error
For more information about this error, try rustc --explain E0425.
Compare this to an equivalent program in Julia
function main() println("hello everynyan!") asdf end
main()
ERROR: LoadError: UndefVarError: asdf not defined Stacktrace: [1] main() @ Main ~/Projects/foo/src/main.jl:3 [2] top-level scope @ ~/Projects/foo/src/main.jl:6 in expression starting at ~/Projects/foo/src/main.jl:6
I love Julia—it's a great programming language—but I think Rust is just beautiful too. (I'll probably use them side by side for stuff.)
Did I mention Rust is also super portable, fast, and has lots of quality documentation, including a free book??? This goddamn crab language is the second coming of christ, and I have no idea why I didn't get started with it sooner.
16 notes · View notes
d0nutzgg · 1 year
Text
Tumblr media
I got most of the base of the CPU worked out on my NES emulator using references to 6502 Assembly and Rust binary arithmetic to implement the 6502 Op Codes. It was hard because originally I didn't update the flags and define the op code functions in the right place because the documentation I was following basically didn't provide the info on where to put it >_> But I wrote my tests at the bottom and in the main.rs file I defined a function that if everything passed on the CPU it would print out "Hello Rusty NES" to show me it works! Today I am going to work a little on RAM management but @emoryvalentine14 and I are going to kill some Roblox zombies soon so it will be after while :D It's going to be a while before the NES emulator is going to be live but I plan to host it on itch.io for 2.99$ along with some NES games I am personally deving in pure 6502 Assembly :| because I am a glutton for punishment.
Also the Discord is now at 70+ members and we are still a very positive community! Loving it. If you want to join shoot me a comment or a message!
Alright folks, I am going to sign off! Will update next update on the NES.
7 notes · View notes
codecraze · 1 year
Text
TCP Server Rust
This is a Rust program that sets up a TCP server to listen for incoming client connections on port 5566. When a client connects to the server and sends a JSON string representing an Employee object, the server deserializes the JSON string and prints the employee's first name to the console.
Here's a breakdown of the code:
The use statements at the top of the file import the necessary Rust modules and dependencies. The serde module is used for serializing and deserializing data, and the std::io and std::net modules are used for handling I/O and network connections.
The Employee struct is defined with three fields: first_name, last_name, and employee_id. The #[derive(Serialize, Deserialize)] attribute macros are used to generate the serde implementations for the struct, which allow it to be serialized and deserialized to and from JSON.
The main function sets up a TCP server using the TcpListener struct and listens for incoming client connections on port 5566. When a client connection is received, a new thread is spawned to handle the connection.
The process_object function is called in the new thread to handle the client connection. The function reads the incoming data from the client, deserializes the JSON string to an Employee object, and prints the employee's first name to the console.
The program uses the try_clone method to create a new handle to the same stream, which allows the function to read the incoming data without consuming the original stream.
The program uses Rust's Result type to handle errors that may occur during I/O operations or JSON deserialization.
Overall, this code demonstrates how to set up a TCP server in Rust and handle incoming client connections, as well as how to serialize and deserialize data to and from JSON using the serde library.
Here is main.rs
Tumblr media Tumblr media
Here is Cargo.toml
Tumblr media
Run the following command in your project directory to build and run the server:
cargo run
Open a new terminal window and connect to the server using a TCP client, such as netcat or telnet. For example, you can run the following command to connect to the server:
telnet 127.0.0.1 5566
Once connected, you can send a message or object to the server. For example, to send a message, simply type a string and press Enter. The server will respond with an acknowledgement message.
To send an object, create a JSON string representing an Employee object and send it to the server using the same connection. The server will deserialize the JSON string and print the employee's first name.
To stop the server, press Ctrl+C in the terminal window where the server is running.
2 notes · View notes
Masterlist
TAGS
Main.re
Main.info
Main.sys
Male Reader.re
GN Reader.re
My Own Fics.sys
FANDOMS
JJBA.re
Haikyuu.re
Saiki K.re
One Piece.re (will edit links and tags soon <3)
0 notes
tinchicus · 2 years
Text
Rust / Primer crate
Hoy si veremos como crear nuestro primer crate, espero les sea de utilidad y buen finde!
Bienvenidos sean a este post, hoy crearmos nuestro primer crate. En el post anterior vimos una descripcion basica de que es un crate, a que equivale en otros lenguajes y como podemos crearlo, dijimos que en lugar de tener un archivo main.rs sera uno llamado lib.rs, tambien las distintas formas que podemos implementarlo, hoy nos centraremos en ver como crear nuestro primer crate y como poder…
Tumblr media
View On WordPress
0 notes
shacklesburst · 3 years
Note
The version control galaxy brain meme should include, "automated backups".
with rotate after every sync to disk!
main.rs main.rs.gz.0 main.rs.gz.1 main.rs.gz.2
2 notes · View notes
sp1tfire · 5 years
Link
1 note · View note
knoldus · 6 years
Link
Why Rust? 
In system programming languages we basically face two complex problems which are difficult to crack i.e. Secure and Multithreaded code. For this Rust has added its own goals of memory safety and data-race-free concurrency.
What Is Rust? 
Rust is a System programing language sponsored by Mozilla which describes it as a “safe,  concurrent and practical language,” supporting functional and imperative-procedural paradigms. It basically focused on three goals i.e. safety, speed, and concurrency.
Rust Prerequisites: 
Syntax: Rust has a concrete syntax similar to C and C++. The blocks of code are delimited by curly brackets, and control flow keywords such as if, else, while and for. Also, there are some new keywords are also introduced such as match(for pattern matching).
Memory safety: Rust is designed to be memory safe and it does not allow null pointers, dangling pointers, or data safe in safe code. Rust core library also provides an option type.
Memory Management: In Rust, there is no automated garbage collection like  Java and other languages.
Hello World Example:
First, we will create a file named main.rs(.rs  is the extension for Rust). And then will write the following the below code.
fn main(){ println!(“Hello World, Welcome to Rust”); }
Now we will run this code snippet with the following command:
$ rustc main.rs $ ./main
Output: Hello World, Welcome to Rust
Above is  hello world code in rust, now we will see what just happen in your “Hello World, Welcome to Rust” program in detail:
In the first line ‘fn’ defines a function in Rust, ‘main’ function is special as it is the beginning for every code in Rust. Here this function doesn’t return any value and also don’t take an argument.
In the second line ‘println!()’ is calling Rust macro, which is how metaprogramming is done in Rust. In Rust when we see ‘!’ means that that is a macro instead of normal function.
Variables In Rust:
In Rust, we use variable binding for assigning a value to a name. Like
let x = 20;
Here x is a variable which is assigned a value 20. But here let is a pattern, not a name i.e we can also use pattern in this way:
let (x, y) = (3, 4);
This means x is 3 and y is 4. By default, a variable is immutable in Rust. That means in, let x = 20;  x is immutable and if we need to make the variable mutable we have to use the mut keyword as explained below
let mut x = 20;  // here x is mutable.
There are many features in Rust which can’t be shared on a single blog so we will be discussing that in my future blogs.
References:
https://en.wikipedia.org/wiki/Rust_(programming_language) https://doc.rust-lang.org/book/second-edition/index.html
Tumblr media
0 notes
nelhagedebugsshit · 6 years
Text
Experience report: Trying to map over over a binary tree in Rust
This story is simplified from an attempt to write an AST walker for a toy compiler, but the essential facts are unchanged.
I am fairly new to Rust (but an experienced C++ programmer) and have been trying to pick up Rust recently. This evening I spent a miserable hour trying to write a function to map an FnMut over a binary tree. I started with a simple tree definition, and try to write what seems to me to be the straightforward code:
use std::rc::Rc; #[derive(Debug)] enum Tree { Leaf(i32), Node(Rc<Tree>, Rc<Tree>), } fn map_tree<F>(tree: &Rc<Tree>, f: F) -> Rc<Tree> where F: FnMut(Rc<Tree>) -> Rc<Tree>, { match &**tree { &Tree::Leaf(_) => f(Rc::clone(tree)), &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, f), map_tree(&r, f))), } } pub fn main() { let tree = Rc::new( Tree::Node(Rc::new(Tree::Leaf(0)), Rc::new(Tree::Leaf(1))), ); let mut sum = 0; map_tree(&tree, |node| { match *node { Tree::Leaf(i) => sum = sum + i, _ => unreachable!() } node }); print!("sum={}", sum); }
(playground link)
I've got a vague premonition that the borrow-checker will yell at me for using f twice in that latter clause, but hey, let's see what it says. It says:
error[E0596]: cannot borrow immutable argument `f` as mutable --> src/main.rs:14:27 | 9 | fn map_tree<F>(tree: &Rc<Tree>, f: F) -> Rc<Tree> | - consider changing this to `mut f` ... 14 | &Tree::Leaf(_) => f(Rc::clone(tree)), | ^ cannot borrow mutably error[E0382]: use of moved value: `f` --> src/main.rs:15:87 | 15 | &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, f), map_tree(&r, f))), | - ^ value used here after move | | | value moved here | = note: move occurs because `f` has type `F`, which does not implement the `Copy` trait
Well, I was right. Let's start by following the first piece of advice, from the E0596:
fn map_tree<F>(tree: &Rc<Tree>, mut f: mut F) -> Rc<Tree> where F: FnMut(Rc<Tree>) -> Rc<Tree>, { match &**tree { &Tree::Leaf(_) => f(Rc::clone(tree)), &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, f), map_tree(&r, f))), } }
(playground link)
First error is resolved, but the second remains unchanged:
error[E0382]: use of moved value: `f` --> src/main.rs:15:87 | 15 | &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, f), map_tree(&r, f))), | - ^ value used here after move | | | value moved here | = note: move occurs because `f` has type `F`, which does not implement the `Copy` trait
Well, I've started to pick up Rust; I know what to do when I'm using a value temporarily and then want to use it again: I probably need more borrows. Because I'm new to this, I forget to borrow mutably:
fn map_tree<F>(tree: &Rc<Tree>, mut f: F) -> Rc<Tree> where F: FnMut(Rc<Tree>) -> Rc<Tree>, { match &**tree { &Tree::Leaf(_) => f(Rc::clone(tree)), &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, &f), map_tree(&r, &f))), } }
(playground link)
This makes that error go away, but replaces it with a different -- very confusing -- spew:
error[E0277]: the trait bound `F: std::ops::Fn<(std::rc::Rc<Tree>,)>` is not satisfied --> src/main.rs:15:57 | 15 | &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, &f), map_tree(&r, &f))), | ^^^^^^^^ the trait `std::ops::Fn<(std::rc::Rc<Tree>,)>` is not implemented for `F` | = help: consider adding a `where F: std::ops::Fn<(std::rc::Rc<Tree>,)>` bound = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&F` note: required by `map_tree` --> src/main.rs:9:1 | 9 | / fn map_tree<F>(tree: &Rc<Tree>, mut f: F) -> Rc<Tree> 10 | | where 11 | | F: FnMut(Rc<Tree>) -> Rc<Tree>, 12 | | { ... | 16 | | } 17 | | } | |_^
Why is std::ops::Fn suddenly appearing? I said FnMut. What is going on?
I eventually google around and realize I need more muts:
fn map_tree<F>(tree: &Rc<Tree>, mut f: F) -> Rc<Tree> where F: FnMut(Rc<Tree>) -> Rc<Tree>, { match &**tree { &Tree::Leaf(_) => f(Rc::clone(tree)), &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, &mut f), map_tree(&r, &mut f))), } }
(playground link)
This now compiles the implementation, but blows up with a recursion limit at the call site!
error[E0275]: overflow evaluating the requirement `[closure@src/main.rs:22:21: 28:6 sum:&mut i32]: std::ops::FnMut<(std::rc::Rc<Tree>,)>` | = help: consider adding a `#![recursion_limit="128"]` attribute to your crate = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut &mut [closure@src/main.rs:22:21: 28:6 sum:&mut i32]` ...
At this point I'm pretty stuck and pretty frustrated.
But I need to break the recursion somehow, so maybe I need to also make map_vars take a reference so the inner and outer calls have the same type? I've not yet mastered Rust syntax, but I know &mut is a thing, and I've already got a mut in the signature, so let's stick an & on it:
fn map_tree<F>(tree: &Rc<Tree>, &mut f: F) -> Rc<Tree> where F: FnMut(Rc<Tree>) -> Rc<Tree>, { match &**tree { &Tree::Leaf(_) => f(Rc::clone(tree)), &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, &mut f), map_tree(&r, &mut f))), } }
(playground link)
New error!
error[E0308]: mismatched types --> src/main.rs:9:33 | 9 | fn map_tree<F>(tree: &Rc<Tree>, &mut f: F) -> Rc<Tree> | ^^^^^^ expected type parameter, found &mut _ | = note: expected type `F` found type `&mut _` = help: did you mean `mut f: &F`?
Well, there's a helpful "did you mean"; let's try that:
fn map_tree<F>(tree: &Rc<Tree>, mut f: &F) -> Rc<Tree> where F: FnMut(Rc<Tree>) -> Rc<Tree>, { match &**tree { &Tree::Leaf(_) => f(Rc::clone(tree)), &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, &mut f), map_tree(&r, &mut f))), } }
(playground link)
No luck, and we're back to complaining about Fn, which I still haven't mentioned anywhere:
error[E0277]: the trait bound `F: std::ops::Fn<(std::rc::Rc<Tree>,)>` is not satisfied --> src/main.rs:15:57 | 15 | &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, &mut f), map_tree(&r, &mut f))), | ^^^^^^^^ the trait `std::ops::Fn<(std::rc::Rc<Tree>,)>` is not implemented for `F` | = help: consider adding a `where F: std::ops::Fn<(std::rc::Rc<Tree>,)>` bound = note: required because of the requirements on the impl of `std::ops::FnMut<(std::rc::Rc<Tree>,)>` for `&F` note: required by `map_tree` --> src/main.rs:9:1 | 9 | / fn map_tree<F>(tree: &Rc<Tree>, mut f: &F) -> Rc<Tree> 10 | | where 11 | | F: FnMut(Rc<Tree>) -> Rc<Tree>, 12 | | { ... | 16 | | } 17 | | } | |_^
At this point I gave up and asked a Rustacean I knew on IRC, who pointed out that I was so close, and yet so far:
fn map_tree<F>(tree: &Rc<Tree>, f: &mut F) -> Rc<Tree> where F: FnMut(Rc<Tree>) -> Rc<Tree>, { match &**tree { &Tree::Leaf(_) => f(Rc::clone(tree)), &Tree::Node(ref l, ref r) => Rc::new(Tree::Node(map_tree(&l, f), map_tree(&r, f))), } }
(playground link)
I can, with the benefit of hindsight, more-or-less understand what happened and the error messages at every step of the way. However, the experience of getting there was really frustrating, notably because at no point did the "did you mean" suggestions actually lead me particularly closer to my goal, and because I had to go by way of a compiler recursion overflow(!) before I could reach a working program.
I want to be really excited about Rust; We nede something that can replace C++'s capacity for powerful zero-cost abstractions and native compilation, while being less ridden with awful memory safety bugs. So far, though, personally, this interaction is honestly about median in terms of my experience trying to write Rust. I'm sure it will get better with time, but right now I'm grumpy.
1 note · View note
miyamoto-ta-blog · 6 years
Text
Rustを学んでみる
Rustを学ぼう
Rust公式によると
Rustは速度、安全性、並行性の3つのゴールにフォーカスしたシステムプログラミング言語です。
とのこと。
実行速度を確保しつつ安全性と並行性に優れている。GoLangとも同じような方向性なのかな。
どうやって学ぶ?
Rustの教材は丁寧に書かれていそうなので、まずはこれをやってみる。
環境構築
環境構築はチュートリアルによると$ curl https://sh.rustup.rs -sSf | shでいいらしい。 なんだけど、仮に気に入らなかったときのことを考えてdockerで環境を作っておきたい。 とりあえずHelloWorldが動くところまでやっておく。
Docker Hub
Docker Hubにrustのオフィシャルイメージがあったのでこれを使ってみる。
環境構築手順
まずはプロジェクトディレクトリを作成。
$ mkdir -p hello_rust_world/src && cd hello_rust_world
次にCargo.tomlを作成する。 このファイルはRustのビルド&パッケージマネージャの設定ファイルになるみたい。 とりあえずHelloWorldが動けばいいので特になにもしていない。
[package] name = "hello_world" version = "0.0.1" authors = ["miyamoto_ta "]
そしてDockerfileを作成する。 中身は、ソースをコンテナ内の/usr/src/myappにコピーして、cargo installでコンパイルしてバイナリを実行する。というもの。
FROM rust:latest WORKDIR /usr/src/myapp COPY . . RUN cargo install CMD ["hello_world"]
src/main.rsを作成する。
fn main() { println!("Hello World!"); }
これで準備ができた。 プロジェクト構成は↓のとおり。
hello_rust_world ├── Cargo.toml ├── Dockerfile └── src └── main.rs
実行手順
準備ができたので、実行してみる。
$ docker build -t my-rust-app . && docker run -ti --rm --name my-runnning-app my-rust-app Sending build context to Docker daemon 4.608kB Step 1/5 : FROM rust:latest ---> 2c6e913a0552 Step 2/5 : WORKDIR /usr/src/myapp ---> Using cache ---> 4d078c2bd97b Step 3/5 : COPY . . ---> 69e941d02d71 Step 4/5 : RUN cargo install ---> Running in 6d13c9772d9f Installing hello_world v0.0.1 (file:///usr/src/myapp) Compiling hello_world v0.0.1 (file:///usr/src/myapp) Finished release [optimized] target(s) in 0.40 secs Installing /usr/local/cargo/bin/hello_world Removing intermediate container 6d13c9772d9f ---> de51c536bd00 Step 5/5 : CMD ["hello_world"] ---> Running in 74162eb39234 Removing intermediate container 74162eb39234 ---> 8a965c6156d2 Successfully built 8a965c6156d2 Successfully tagged my-rust-app:latest Hello World!
とりあえず動く環境は作れた。
0 notes
kjunichi · 7 years
Text
rust-aobench/main.rs at master · sharow/rust-aobench · GitHub [はてなブックマーク]
rust-aobench/main.rs at master · sharow/rust-aobench · GitHub
/* -*- Mode: rust; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
kjw_junichi プログラミング, 画像処理 Pixelの1次元配列として定義している
from kjw_junichiのブックマーク http://ift.tt/2mhfY8Y
0 notes
tinchicus · 2 years
Text
Rust / struct en multiples archivos
Ayer hablamos sobre los struct pero hoy les traigo un ejemplo de como se utilizan en la vida real, espero les sea de utilidad!
Bienvenidos sean a este post, hoy veremos como se implementa realmente a struct. En el post anterior vimos una forma practica de definir un par de struct para nuestro codigo pero en la vida real tendremos unos mas grandes y en mayor cantidad, lo cual hara a nuestro archivo main.rs impractico, para resolver esto se crea un archivo por cada struct y luego los incluiremos desde el main para…
Tumblr media
View On WordPress
0 notes
Tumblr media
Oversized
Character: Tanaka Ryuunosuke (Haikyuu)
AU: Time Skip, Canonverse
Genre: Fluff
Word Count: 676
Prompt: Fluff #14) “Stop stealing my clothes.”
Pronouns: He/Him
CW: Reader is short (about 5’4) and a femboy, cos why not.
Notes: This was requested by a friend to help me get into the swing of things, so it mostly caters to him.
---------
Tanaka Ryuunosuke adored his boyfriend. He was short and thin, his voice was almost as soft as his personality, and god, when Tanaka would watch him getting ready, his smile would never leave his face.
Y/N would spend so much time carefully picking out his outfit. His eyes scanning over every piece in front of him.
“Babe, skirt or shorts today?” He’d usually ask. Tanaka loved helping Y/N pick out his outfit, choosing from the selection of pinks, purples, reds, blues, and various other soft colors.
Today, however, Ryu wasn’t here to help him pick out his outfit. You see, Tanaka was staying the night with Noya and the other guys from the team who were in their year. So Y/N was stuck home alone for the night and half the day.
It’d be a lie if he said he wasn’t bored, his body was thrown over the couch lazily as he scrolled through his phone. He eventually lifted his head in determination.
Sure, he was told before not to, but maybe just this once he could get away with it? I mean, Tanaka wouldn’t be home for another, what, 4 hours? He had plenty of time.
And with that, he waltzed into their shared bedroom.
Now, you may be confused, so I’ll clarify; Y/N is a little clothes snatcher. Yeah. He has had the habit, all through the 4 years of being with Tanaka, of stealing the poor man’s clothes. He’d gotten out of said habit, but there’s still that lingering want to be in his boyfriend's clothes.
His hand moved across the many items in the closet. Tanaka’s clothes mainly consisted of darker clothes with the occasional bright neon shirt or jacket. Finally, his hand stopped on his favorite one. It was a light grey hoodie with the logo of some random company he’d never heard of. It was the smallest one Tanaka owned, and naturally, Y/N would want it. However, Tanaka wouldn’t give it to him, stating that he still wore it. And that he did.
The hoodie always smelled of Tanaka’s strong scent. The one Y/N would always smell at night when Tanaka holds him or when they’re cuddling on the couch. Y/N quickly removed his current cropped jacket and pushed his arms through the sleeves. A smile quickly found its way upon his face as his head popped through the hole.
Tanaka’s scent wound its way around his body, filling his nose with that comforting smell that he loves. He flopped onto the bed, quickly snuggling into the hoodie. His face now adorning a permanent smile.
That is until the bedroom door opened. Y/N quickly jumped up, the noise scaring him. However, once he saw who was in the doorway, he felt ashamed.
There stood Tanaka, with a face Y/N couldn’t quite make out yet. But he knew he was in trouble, he shouldn’t have put the hoodie on…
“Wha- Y/N-” His eyes were wide, his body taking up a good portion of the doorway.
Y/N looked down, feeling bad. When he felt the bed dip next to him though, his head shot up to look at his lover. He quickly noticed the soft look on his face and the light blush that covered his cheeks.
“I thought I already told you. Stop stealing my clothes.” A smile quickly wound its way up to Tanaka’s face. His hand softly grabbed Y/N’s jaw and pulled him forward in a small peck.
“I thought I might have more time,” Y/N said with a pout.
Tanaka let out a little chuckle as he moved back. “Yeah? Well, I’m glad I didn’t tell you I was comin’ home early. Otherwise, I would’ve missed this wonderful sight.”
Y/N groaned and lightly shoved Tanaka, a blush now adorning his cheeks.
“You cheese ball.” They both giggled some before it grew quiet. “Can I keep the hoodie now?”
“Yes, Y/N. You can keep it.” Tanaka let out an affectionate sigh as Y/N giggled some more and laid his head on Tanaka’s shoulder.
“Am I really that cheesy-?”
“Ryu-”
Tumblr media
Request by: @your-local-catboy
535 notes · View notes
Could you do an red imposter x gn!reader with the prompt
10) "is that my shirt?" "you mean our shirt"
/srs
bawling my eyes out oh my god
~~~
Type: Fluff (a bit of hinting at the end)
Prompt: "Is that ny shirt?" "You mean our shirt."
Character(s): The Red Imposter
Reader: GN, no pronouns
Word Count: idk i physically cannot
A/N: not beta read or proof read. I was in agony the whole time i wrote this, Daniel.
~~~
The crew was in a sort of delemna. You see, you and your buddies were on a mission in space, but suddenly your mates started disappearing. Your crew suspected someone was behind it, as bodies were found left behind. And so here you all were, gathered around the table in the center of the cafeteria.
"I think it's purple. All he does is sit in the electrical room in silence. I could've sworn I saw him jump around the corner when I went to fix the lights!" Yellow accused.
"As if! You were the one who was fiddling with the switches when I came to help!" Orange jumped in.
Pink now joined in, "Pricless. You followed me all around the ship until I finally found White!"
"Woah, don't drag me into this, guys!" You suddenly exclaimed. No way were they gonna bring you into their argument. You hadn't even seen them in the first place.
"Alright guys, I think we all need a breather. Lets head back to our rooms for now." Red interjected. You couldn't help but let your gaze linger. He looked great in his skin tight suit.
His eyes met yours and you looked away swiftly. Of course he'd catch you looking, just your luck.
The group began to separate, heading to their quarters to rest. You quickly tried to disappear down the hall, but was promptly stopped by Blue.
"Do you have any idea who could be behind this, White? We've already lost Black, Green, and Cyan..." she whispered, leaning in to be sure no one listens in.
"No, I don't have any suspicions." You wanted to hurry and be back in your room before Red gets there. Yes, you share a room. But all you want right now is to change into some actual clothes and get comfy.
"I personally think it's Red. You be careful tonight, yes?" Blue then turned and quickly made her way to her room she shared with Yellow and Pink.
Orange gave you the side eye making his way to his room with Purple.
Sighing, you opened the door to your room. And luckily for you, Red wasn't back yet. Glancing around the room, you noticed one of his plain red shirts laying on the floor.
You didn't care if it were clean or worn, you just had to wear it. And so you scooped it up, tearing off your suit and slipped his on.
As you were turning around, Red opened the door and froze. You two stared at each other for who knows how long.
Finally, Red spoke up, "Is... Is that my shirt?"
In a quick reply, you confidently said "You mean our shirt."
Red's eyes widened for a split second before returning to his usual bored expression. Only now, it had a playful squint in the eyes.
"Oh yeah? If what's mine is yours than what's yours is mine, no?" He made his way to you, leaving barely any room between you two. "That means these too."
He passionately presses his lips to yours, hands resting on your hips.
Pulling away, your face was beet red.
"Not so cocky now, huh?"
41 notes · View notes
Am I Crazy?
Tumblr media
Lev Haiba x Reader
CW: Slight angst. This is based on a breakdown I had the night before I wrote this. As of writing this, it was 6 hours ago.
Reader doesn’t use pronouns.
AU Unknown
Reader goes to Fukorodani and is a 2nd year. Reader and Lev are already together.
------
You didn’t know what was wrong. You could breathe just fine, but your mind was racing. Your body was calm, but your heart was pumping. You made no noises and yet tears ran down your face. So then what was it?
Nothing felt real. You heard things you shouldn’t. Saw things you shouldn’t. Felt things you shouldn’t. It was currently 3-ish in the morning and you still can’t sleep. This was usual, yes, but it was different this time. Usually, you stayed up because you were stubborn or your mind wouldn’t shut up. But this time, it wasn’t you who couldn’t shut up.
Voices spoke to you in the darkness. Who were they? What are they saying? Why are they talking to me? Why now? Why won't they stop?
You quickly grabbed your phone, turning on the flashlight to shine it around your room.
No one. Of course. What did you expect? A cult to be standing around your bed, whispering? What a joke.
You turned and laid down again, moving to message your boyfriend. You knew Lev wouldn’t hesitate to come over if you needed him. He knows of your sleeping habits and has come over multiple times after dark to help you sleep.
You sent a simple “come over” and almost instantly received an “omw!” back. He must’ve been awake.
As soon as you put the phone down, the hands began again. Hands touching your feet, feeling your legs, sharp pains as if nails were being driven into your feet. You knew they weren’t real. You knew they were just imaginary like everything else was. And yet it felt so real. Your heart was racing again, left helpless until you heard that soft rapping at the window.
Almost instantaneously, the touches left your legs. The noises all stopped. It all left you as if they knew someone else was here. As if they wanted only you to know of their existence. Like they want everyone to think you’re crazy for hearing them, because they weren’t real, and they never, ever were.
Crazy...?
Were you… Were you crazy?
The knocking sounded again, snapping you back to reality. You rushed to open the window so your lover could wiggle his long body through the hole. Once he was grounded, his hands found your shaking body. Hands made their place on your back, head leaning on top of your head. You were pretty tall, tall enough to the point that Lev doesn’t have to bend much to reach.
“What’d you need, Y/N?” His voice came out a bit louder than a whisper, but still small nonetheless. You shrugged numbly, leaning your weight onto him. He briefly shifted so that the two of you could fall safely onto your bed. Both of you laid on your sides, Lev still holding onto you.
You didn’t speak, didn’t dare. You couldn’t explain this to him, he’d think you were… crazy…
You only buried your face further into his thin frame. He may have the height advantage, but you had the muscle and fat advantage, you weren’t super overweight, but had a bit of a tummy and still harbored some baby fat here and there.
“Y/N? What happened?” You could feel him shifting, attempting to see your face. You lifted it slightly, just to where you could just barely see his face.
“I… I kept hearing things.” You mumbled out a short explanation.
“Hearing things? What do you mean? Like, cars? Animals? Creaks?”
“Voices.”
Lev was silent for a bit, and then; “Voices? Like, your parents talking? Or your sister playing?” You had to explain further.
“I don’t know these voices. None of the sounds. I hear people knocking on my door. People walking past it, People standing in the corner whispering. Sometimes I… Sometimes I can feel people touching my legs, grabbing my feet, digging their nails into me. I see things moving when I don’t look directly at them. I can feel eyes watching me at all times. They never stop, Lev. Never.” At this point, the tears had begun to fall again. It terrified you, things like this happening. You didn’t know what anything was anymore.
“Oh, Y/N… I’m here, ok? Nothing can get you while I’ve got you. No one can hurt you, I’m here to stop them. Have you gotten to sleep at all?” His grip tightened as you shook your head solemnly. Your mind kept telling you that you couldn’t sleep with the people there.
“Y/N you ne-”
“Am I crazy?” You blurted out.
“...What?”
“Am I… crazy, Lev?” Your body moved closer to his, seeking his comfort.
“Well…” He hesitated for a second. “It depends. Crazy for what you're hearing and stuff, I’m not sure. I don’t know what this is. But, crazy to think anything could, no, anything would hurt you? Yes, you are.”
“Lev…” You groaned. Of course he’d find a way to be cheesy. It’s nothing new, of course.
“Y/N, you aren’t crazy. It’s ok to be scared. But I promise nothing's gonna do anything, alright?”
You nodded as he cuddled up closer to you, “Will you stay the rest of the night?”
“Of course I will, Y/N. There’s no way I’m making that trip back. You’d have to kick me out!” That elicited a small giggle out of you. He always ended up making it better in the end.
“Sleep, Y/N.”
“Yeah…” You could feel his large hand move to run through your hair, helping drift you off to sleep, finally, for the night.
98 notes · View notes
Tumblr media
Character: Ennoshita Chikara
Au: Royal
Genre: Fluff w/a bit of Crack
Word Count: 1,163
Pronouns: Probably not mentioned, but if it is, I used they/them!
CW: Reader is tall (about 5’8) and that's about it for this part.
Notes: This will be a three part story: the main story line and two endings. Each post will be separate but I’ll link both endings on this post once I have them out and I’ll link them to each other as well as the main post. Again, this was requested by a friend to help with practice. So this caters to them!
Message to Roy: You didn’t specify which royal AU you wanted, so I took the liberty of doing whatever came to mind as I wrote.
---------
The sound of birds filled your ears as you walked through the garden. It was well kept, with various species of plants growing on almost every square inch of the garden. The path you walked was made from stones, none of them the same size or shape.
The air was warm, the smell of spring itself was extravagant. Your senses were full of the sound, smell, and sight of nature. You haven’t been able to get out much lately, as the past week has been nothing but almost constant storms. Finally, though, you were able to walk the gardens again. It was your favorite place, the only quiet you can get in this giant, bustling castle.
Yes, you heard me right. You lived in a castle. However, I regret to inform you that you aren’t the royalty running this said castle. No, you’re but a mere servant. A kitchen servant? No no no, you were the gardener. Yes, this garden, this beauty, it’s all because of you.
Speaking of royalty, the group of princes had walked through the gates of the garden. None of them were blood-related but adopted. The group consisted of the middle children; Ryuunosuke Tanaka, Yuu Nishinoya, Hisashi Kinoshita, Kazuhito Narita, and, of course, Chikara Ennoshita.
Ennoshita has always had a fondness for this garden. He’d come out here the most out of anyone in this dreadful castle, aside from you, of course. More than once, you two had struck up a conversation. He isn’t very talkative around you though. You’ve wondered why, but never bothered to ask.
His love for your garden, for your work, has brought him to become your favored choice out of them all. He was respectful and never touched your plants. The others, however, they touched and they plucked and they would occasionally stomp all over your hard work.
You let out a tired sigh, it was still early, why’d they have to come now of all times? You turned away and made your way towards the small pond in the very center of the garden. Tiny flowers had grown around it.
The voices of the boys got louder as they got closer. When they were back into your view, you caught Ennoshita waving slightly at you in a friendly greeting. Yeah, he was definitely your favorite. You shot him a soft smile in return, and he quickly turned back to look at his companions as the shortest one started jumping at the others and yelling.
“But it’s a great chance to see girls, Tanaka! You gotta come! I can’t go alone again!” Nishinoya now clung onto Tanaka as he was resting on his back, much to Tanaka’s apparent displeasure.
“C’mon, we should all go, it won't be that bad. Tanaka, you haven’t come to the past few, anyways. You have to come to at least one this year.” Kinoshita said his part.
“See, you gotta come this time Ryu!” The short one continued wiggling on the poor boy’s back.
“Guys, come one, calm down.” Narita raised his hands and smiled nervously, motioning his head towards where you sat, listening and occasionally glancing over.
“I got better things to do that night.” He retaliated.
“Tanaka, you can’t miss another one. This is important for the image of our kingdom and us.” Ennoshita cut in.
Their voices drowned into the background as you watched the water, mind wandering. What they were referring to was the big party happening two days from now. This particular one was planned to bring four of the surrounding kingdoms together. It can be used to court or form bonds, but you were most worried about getting the correct flowers together for the event. Every time, you are put in charge of flowers, seeing as it’s your expertise.
You thought back, going over your list a few more times. You had to make sure it was perfect or you could get into serious trouble.
Your thoughts were interrupted by a cough nearby. You glanced up to find none other than ennoshita walking closer, a timid smile on his face.
“Good morning, Y/N. Sorry for all the noise earlier.” His voice was smaller around you than it is around anyone else.
You smiled at him slightly, nodding in acknowledgment to the boy. He quietly sat near you, watching the sky as birds flew overhead. The silence was nice, it was something you always liked about him. He never forced conversation.
“What about you, the party I mean. Are you going to attend this time?” He was watching you intently, waiting for your answer.
“I’m… I’m not sure. I don’t really like all the noise. And there’s always way too many people attending…” You brought your hands to rest in your lap, fidgeting nervously. You’d never been one for crowds. You’d grown up in the quiet part of town, there weren’t many residents and the shops were never very busy.
“I see.” If you hadn’t known any better, you’d think he sounded disappointed. As if he wanted you to come. “That’s too bad, but I’m assuming you’ll be out here instead?”
You glanced back over at him to find a teasing smile and playful eyes watching you. You’d be lying if you said you didn’t find it amusing.
“You could say that. Though I’ll probably find my way to the food when it’s put out.” Your mood was now matching his in terms of playfulness. His soft laughter filled the morning air, a sound you had come to love.
Wait.
Love?
Maybe ‘like’ is the more… appropriate word for this.
However you may feel, he was one of the princes, you were just a gardener. You’re extremely lucky to even get moments like this.
The silence returned when his laughter died down, now only bearing a soft smile and soft eyes as he looked around at the plants.
“I’ve always loved this place, you know? It’s quiet out here.” He looked like he wanted to add something else, but shook his head deciding against it. “It's calm, serene. I couldn’t imagine spending my mornings anywhere else.”
Your face grew warm at his words. Though they weren’t directed at you, about you, they were about this place you’ve worked so hard to protect and keep beautiful. The compliment about your work made you quiet, face a tiny shade darker and smile nervous.
Ennoshita sighed, causing you to look up at him. His face was disappointed as he was looking in the direction of loud laughter and shouting.
“I really don’t like bringing them here…” He slowly stood, glancing at you with a smile. “If you’ll excuse me, I have man-babies to watch over.”
You let a snort leave you, noticing how his smile grew when he heard it. You nodded once at each other and he swiftly left. A moment later, you heard his voice yelling a short “Shut up idiots!”
Being left alone made your mind wander back to his question. Should you go…?
Tumblr media
Will link the endings when I release them!!!
Request by: @fukoronoko !!! ilysm
39 notes · View notes