GetWiki
Rust (programming language)
ARTICLE SUBJECTS
being →
database →
ethics →
fiction →
history →
internet →
language →
linux →
logic →
method →
news →
policy →
purpose →
religion →
science →
software →
truth →
unix →
wiki →
ARTICLE TYPES
essay →
feed →
help →
system →
wiki →
ARTICLE ORIGINS
critical →
forked →
imported →
original →
Rust (programming language)
please note:
- the content below is remote from Wikipedia
- it has been imported raw for GetWiki
{{Short description|General-purpose programming language}}{{Good article}}{{Use American English|date=July 2022}}{{Use mdy dates|date=July 2022|cs1-dates=y}}- the content below is remote from Wikipedia
- it has been imported raw for GetWiki
factoids | |||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
name | Rust| logo = Rust programming language black logo.svg| logo alt = Rust logo; a capital letter R set into a sprocket | Rust Foundation | property | reference | P348{edih} | {edih}| programming language = Rust | Cross-platform software>Cross-platform{{refn | Including build tools, host tools, and standard library support for x86-64, ARM architecture family | , MIPS architecture>MIPS, RISC-V, WebAssembly, P6 (microarchitecture) | , AArch64, PowerPC, and Linux on IBM Z>s390x.PLATFORM SUPPORT >WEBSITE=THE RUSTC BOOK | ACCESS-DATE=2022-06-27, }} | Cross-platform software>Cross-platform{{refn | Including Windows, Linux, macOS, FreeBSD, NetBSD, and Illumos. Host build tools on Android (operating system) | , iOS, Haiku (operating system)>Haiku, Redox (operating system) | , and Fuchsia (operating system)>Fuchsia are not officially shipped; these operating systems are supported as targets.}} | MIT License>MIT and Apache License | {{refn>group=note | LLVM or MSVC, are subject to their own licenses.THE RUST PROGRAMMING LANGUAGE | PUBLISHER=THE RUST PROGRAMMING LANGUAGE, 19 October 2022, }}| file ext = .rs, .rlib |
Alef|
}}C#| C++| Cyclone| ElmWEB, Uniqueness Types,weblink 2016-10-08, Rust Blog, "Those of you familiar with the Elm style may recognize that the updated {{mono, --explain, messages draw heavy inspiration from the Elm approach."}}| Erlang| Haskell| Limbo| Newsqueak| OCaml| Ruby| Scheme| Standard ML| Swift |
IdrisWEB, Uniqueness Types,weblink 2022-07-14, Idris 1.3.3 documentation, "They are inspired by ... ownership types and borrowed pointers in the Rust programming language.", |
}}}}Rust is a multi-paradigm, general-purpose programming language that emphasizes performance, type safety, and concurrency. It enforces memory safetyâmeaning that all references point to valid memoryâwithout a garbage collector. To simultaneously enforce memory safety and prevent data races, its "borrow checker" tracks the object lifetime of all references in a program during compilation.Rust was influenced by ideas from functional programming, including immutability, higher-order functions, and algebraic data types. It is popular for systems programming.BOOK, Eshwarla, Prabhu,weblink Practical System Programming for Rust Developers: Build fast and secure software for Linux/Unix systems with the help of practical examples, 2020-12-24, Packt Publishing Ltd, 978-1-80056-201-1, en, BOOK, Blandy, Jim,weblink Programming Rust: Fast, Safe Systems Development, Orendorff, Jason, 2017-11-21, O'Reilly Media, Inc., 978-1-4919-2725-0, en, JOURNAL, Blanco-Cuaresma, Sergi, Bolmont, Emeline, 2017-05-30, What can the programming language Rust do for astrophysics?,weblink Proceedings of the International Astronomical Union, en, 12, S325, 341â344, 10.1017/S1743921316013168, 1702.02951, 2017IAUS..325..341B, 7857871, 1743-9213, Software developer Graydon Hoare created Rust as a personal project while working at Mozilla Research in 2006. Mozilla officially sponsored the project in 2009. In the years following the first stable release in May 2015, Rust was adopted by companies including Amazon, Discord, Dropbox, Google (Alphabet), Meta, and Microsoft. In December 2022, it became the first language other than C and assembly to be supported in the development of the Linux kernel.Rust has been noted for its rapid adoption,JOURNAL, Perkel, Jeffrey M., 2020-12-01, Why scientists are turning to Rust,weblink Nature (journal), Nature, en, 588, 7836, 185â186, 10.1038/d41586-020-03382-2, 33262490, 2020Natur.588..185P, 227251258, May 15, 2022, May 6, 2022,weblink live, and has been studied in programming language theory research.WEB, Computer Scientist proves safety claims of the programming language Rust,weblink 2022-05-15, EurekAlert!, en, February 24, 2022,weblink live, JOURNAL, Jung, Ralf, Jourdan, Jacques-Henri, Krebbers, Robbert, Dreyer, Derek, 2017-12-27, RustBelt: securing the foundations of the Rust programming language, Proceedings of the ACM on Programming Languages, 2, POPL, 66:1â66:34, 10.1145/3158154, 215791659, free, 21.11116/0000-0003-34C6-3, free, THESIS, Jung, Ralf, 2020, Understanding and evolving the Rust programming language,weblink en, 10.22028/D291-31946, May 15, 2022, March 8, 2022,weblink live, PhD, Saarland University, Project Verona| Spark| Swift| VWEB, V documentation (Introduction),weblink 2023-11-04, GitHub, en, | ZigWEB, Yegulalp, Serdar, 2016-08-29, New challenger joins Rust to topple C language,weblink 2022-10-19, InfoWorld, en, | HistoryFile:MozillaCaliforniaHeadquarters.JPG|thumb|right|Mozilla Foundation headquarters in Mountain View, CaliforniaMountain View, CaliforniaOrigins (2006â2012)Rust began as a personal project in 2006 by Mozilla Research employee Graydon Hoare.WEB,weblink How Rust went from a side project to the world's most-loved programming language, Thompson, Clive, 2023-02-14, MIT Technology Review, en, 2023-02-23, Mozilla began sponsoring the project in 2009 as a part of the ongoing development of an experimental browser engine called Servo,WEB, Avram, Abel, 2012-08-03, Interview on Rust, a Systems Programming Language Developed by Mozilla,weblink live,weblink" title="web.archive.org/web/20130724045852weblink">weblink 2013-07-24, 2013-08-17, InfoQ, which was officially announced by Mozilla in 2010.WEB, Asay, Matt, 2021-04-12, Rust, not Firefox, is Mozilla's greatest industry contribution,weblink 2022-07-07, TechRepublic, en-US, CONFERENCE, Hoare, Graydon, Project Servo, Mozilla Annual Summit 2010, 7 July 2010, Whistler, Canada,weblink 22 February 2017, 11 July 2017,weblink" title="web.archive.org/web/20170711131514weblink">weblink live, Rust's memory and ownership system was influenced by region-based memory management in languages such as Cyclone and ML Kit.Around the same time, work shifted from the initial compiler written in OCaml to a self-hosting compiler based on LLVM written in Rust. The new Rust compiler successfully compiled itself in 2011.{{Better source needed|date=March 2024}} In the fall of 2011, the Rust logo was developed based on a bicycle chainring.WEB, Rust logo,weblink bugzilla.mozilla.org, 2 February 2024,Evolution (2012â2020)Rust's type system underwent significant changes between versions 0.2, 0.3, and 0.4. In version 0.2, which was released in March 2012, classes were introduced for the first time.WEB, Hoare, Graydon, 2012-03-29, [rust-dev] Rust 0.2 released,weblink 2024-04-04, 2022-11-06,weblink mail.mozilla.org, Four months later, version 0.3 added destructors and polymorphism, through the use of interfaces.WEB, Hoare, Graydon, 2012-07-12, [rust-dev] Rust 0.3 released,weblink 2022-06-12, mail.mozilla.org, 2022-08-24,weblink dead, In October 2012, version 0.4 was released, which added traits as a means of inheritance. Interfaces were combined with traits and removed as a separate feature; and classes were replaced by a combination of implementations and structured types.WEB, Hoare, Graydon, [rust-dev] Rust 0.4 released,weblink live,weblink October 31, 2021, 2021-10-31, mail.mozilla.org, October 15, 2012, Through the early 2010s, memory management through the ownership system was gradually consolidated to prevent memory bugs. By 2013, Rust's garbage collector was removed, with the ownership rules in place.In January 2014, the editor-in-chief of Dr. Dobb's Journal, Andrew Binstock, commented on Rust's chances of becoming a competitor to C++, along with D, Go, and Nim (then Nimrod). According to Binstock, while Rust was "widely viewed as a remarkably elegant language", adoption slowed because it radically changed from version to version.NEWS, Binstock, Andrew, January 7, 2014, The Rise And Fall of Languages in 2013, Dr. Dobb's Journal,weblink live,weblink" title="web.archive.org/web/20160807075745weblink">weblink 2016-08-07, 2022-11-20, The first stable release, Rust 1.0, was released on May 15, 2015.WEB, Version History, GitHub,weblink 2017-01-01, 2015-05-15,weblink live, WEB,weblink Announcing Rust 1.0, Rust Blog, The Rust Core Team, May 15, 2015, 2015-12-11, 2015-05-15,weblink" title="web.archive.org/web/20150515171337weblink">weblink live, The development of the Servo browser engine continued alongside Rust's own growth. In September 2017, Firefox 57 was released as the first version that incorporated components from Servo, in a project named "Firefox Quantum".WEB, Lardinois, Frederic, 2017-09-29, It's time to give Firefox another chance,weblink 2023-08-15, TechCrunch, en-US,Mozilla layoffs and Rust Foundation (2020âpresent)In August 2020, Mozilla laid off 250 of its 1,000 employees worldwide, as part of a corporate restructuring caused by the COVID-19 pandemic.WEB,weblink Mozilla lays off 250 employees while it refocuses on commercial products, Cimpanu, Catalin, ZDNet, 2020-12-02, 2020-08-11, March 18, 2022,weblink live, WEB,weblink Mozilla lays off 250 employees due to the pandemic, Engadget, Cooper, Daniel, 2020-12-02, 2020-08-11, 2020-12-13,weblink live, The team behind Servo was disbanded. The event raised concerns about the future of Rust, as some members of the team were active contributors to Rust.WEB, Tung, Liam, Programming language Rust: Mozilla job cuts have hit us badly but here's how we'll survive,weblink 2022-04-21, ZDNet, en, April 21, 2022,weblink live, In the following week, the Rust Core Team acknowledged the severe impact of the layoffs and announced that plans for a Rust foundation were underway. The first goal of the foundation would be to take ownership of all trademarks and domain names, and take financial responsibility for their costs.WEB,weblink Laying the foundation for Rust's future, Rust Blog, 2020-12-02, 2020-08-18, 2020-12-02,weblink live, On February 8, 2021, the formation of the Rust Foundation was announced by its five founding companies (AWS, Huawei, Google, Microsoft, and Mozilla).WEB, 2020-02-08, Hello World!,weblink 2022-06-04, Rust Foundation, en, April 19, 2022,weblink live, WEB, 2021-02-09, Mozilla Welcomes the Rust Foundation, Mozilla Blog,weblinkweblink 2021-02-08, 2021-02-09, live, In a blog post published on April 6, 2021, Google announced support for Rust within the Android Open Source Project as an alternative to C/C++.WEB, Amadeo, Ron, 2021-04-07, Google is now writing low-level Android code in Rust,weblink 2021-04-08, Ars Technica, en-us, 2021-04-08,weblink live, On November 22, 2021, the Moderation Team, which was responsible for enforcing community standards and the Code of Conduct, announced their resignation "in protest of the Core Team placing themselves unaccountable to anyone but themselves".WEB, Tim, Anderson, Entire Rust moderation team resigns,weblink 2021-11-23, 2022-08-04, The Register, en, In May 2022, the Rust Core Team, other lead programmers, and certain members of the Rust Foundation board implemented governance reforms in response to the incident.WEB, Governance Update,weblink 2022-10-27, Inside Rust Blog, en, The Rust Foundation posted a draft for a new trademark policy on April 6, 2023, revising its rules on how the Rust logo and name can be used, which resulted in negative reactions from Rust users and contributors.WEB, Claburn, Thomas, Rust Foundation apologizes for trademark policy confusion, 2023-04-17,weblink 2023-05-07, The Register, en,Syntax and featuresRust's syntax is similar to that of C and C++,WEB, Proven, Liam, 2019-11-27, Rebecca Rumbul named new CEO of The Rust Foundation,weblink 2022-07-14, The Register, en, "Both are curly bracket languages, with C-like syntax that makes them unintimidating for C programmers.", although many of its features were influenced by functional programming languages.{{sfn|Klabnik|Nichols|2019|p=263}} Hoare described Rust as targeted at "frustrated C++ developers" and emphasized features such as safety, control of memory layout, and concurrency. Safety in Rust includes the guarantees of memory safety, type safety, and lack of data races.Hello World programBelow is a "Hello, World!" program in Rust. The {{Rust|fn}} keyword denotes a function, and the println! macro prints the message to standard output.{{sfn|Klabnik|Nichols|2019|pp=5â6}} Statements in Rust are separated by semicolons.fn main() {
println!("Hello, World!");
}Keywords and control flowIn Rust, blocks of code are delimited by curly brackets, and control flow is implemented by keywords including if, else, while, and for.{{sfn|Klabnik|Nichols|2019|pp=49â57}} Pattern matching can be done using the {{Rust|match}} keyword.{{sfn|Klabnik|Nichols|2019|pp=104â109}} In the examples below, explanations are given in comments, which start with {{code|//}}.{{sfn|Klabnik|Nichols|2019|p=49}}fn main() {
// Defining a mutable variable with 'let mut'
// Using the macro vec! to create a vector let mut values = vec![1, 2, 3, 4];
for value in &values {
println!("value = {}", value); }
if values.len() > 5 {
println!("List is longer than five items"); }
// Pattern matching
match values.len() { 0 => println!("Empty"), 1 => println!("One value"), // pattern matching can use ranges of integers 2..=10 => println!("Between two and ten values"), 11 => println!("Eleven values"), // A `_` pattern is called a "wildcard", it matches any value _ => println!("Many values"), };
// while loop with predicate and pattern matching using let
}while let Some(value) = values.pop() { println!("value = {value}"); // using curly brackets to format a local variable } Expression blocksRust is expression-oriented, with nearly every part of a function body being an expression, including control-flow operators.{{sfn|Klabnik|Nichols|2019|pp=50â53}} The ordinary if expression is used instead of (?:|C's ternary conditional). With returns being implicit, a function does not need to end with a return expression; if the semicolon is omitted, the value of the last expression in the function is used as the return value,WEB, Tyson, Matthew, 2022-03-03, Rust programming for Java developers,weblink 2022-07-14, InfoWorld, en, as seen in the following recursive implementation of the factorial function:fn factorial(i: u64) -> u64 {
if i == 0 {
}The following iterative implementation uses the ..= operator to create an inclusive range:fn factorial(i: u64) -> u64 {
1 } else { i * factorial(i - 1) }
(2..=i).product()
}Closures{{excerpt|Anonymous function|Rust|subsections=yes}}TypesRust is strongly typed and statically typed. The types of all variables must be known at compilation time; assigning a value of a particular type to a differently typed variable causes a compilation error. Variables are declared with the keyword let, and type inference is used to determine their type.{{sfn|Klabnik|Nichols|2019|pp=24}} Variables assigned multiple times must be marked with the keyword mut (short for mutable).{{sfn|Klabnik|Nichols|2019|pp=32â33}}The default integer type is {{rust|i32}}, and the default floating point type is {{rust|f64}}. If the type of a literal number is not explicitly provided, either it is inferred from the context or the default type is used.{{sfn|Klabnik|Nichols|2019|pp=36â38}}Primitive types {| class"wikitable" | ||
bool}}|Boolean value |
}}
| ||||||||||||||||||||||
u8}}|Unsigned 8-bit integer (a byte) |
}}
| ||||||||||||||||||||||
}}
| Signed integers, up to 128-bit computing>128 bits |
}}
| |||||||||||||||||||||
}}
| Unsigned integers, up to 128-bit computing>128 bits |
}}
| |||||||||||||||||||||
}}
| Pointer (computer programming)>Pointer-sized integers (size depends on platform) |
}}
| |||||||||||||||||||||
}}
| Floating-point arithmetic>Floating-point numbers |
}}
| |||||||||||||||||||||
char}} |
}}
|
}}
| |||||||||||||||||||||
str}} | UTF-8-encoded string slice, the primitive string type. It is usually seen in its borrowed form, {{Rust>&str}}. It is also the type of string literals, {{Rust | ACCESS-DATE=2023-06-23, doc.rust-lang.org, |
}}
| ||||||||||||||||||||
[T; N]}} | Array (data structure)>Array â collection of N objects of the same type T, stored in contiguous memory |
}}
| |||||||||||||||||||||
[T]}} | ACCESS-DATE=2023-06-23, doc.rust-lang.org, |
}}
| |||||||||||||||||||||
{{Rust|(T, U, ..)}}}}|Tuple â a finite heterogeneous sequence |
}}
| ||||||||||||||||||||||
!}} | Bottom type>Never type (unreachable value) | let x {{=}} { return 123 };}} |
Standard library {| class"wikitable"|+Summary of Rust's types in the standard library
!Type!Description!Examples- {{Rust|String::new(){edih}
- {{Rust|String::from("Hello")}}
- {{Rust|"ð¦ð¦ð¦".to_string()}}
}}
- {{Rust|OsStr{edih}
- {{Rust|OsString}}
}}
- {{Rust|OsStr::new("Hello"){edih}
- {{Rust|OsString::from("world")}}
}}
- {{Rust|Path{edih}
- {{Rust|PathBuf}}
}}
- {{Rust|Path::new("./path/to")}}
- {{Rust|PathBuf::from(r"C:.pathto")}}
}}
- {{Rust|CStr{edih}
- {{Rust|CString}}
}}
- {{Rust|c"Hello"{edih}
- {{Rust|CStr::from_bytes_with_nul(b"Hello ").unwrap()}}
- {{Rust|CString::new("world").unwrap()}}
}}
- {{Rust|Vec::new(){edih}
- {{Rust|vec![1, 2, 3, 4, 5]}}
}}
- {{Rust|None{edih}
- {{Rust|Some(3)}}
- {{Rust|Some("hello")}}
}}
- {{Rust|Ok(3){edih}
- {{Rust|Err("something went wrong")}}
}}
let (lock, cvar) = (Mutex::new(true), Condvar::new());
// As long as the value inside the `Mutex` is `true`, we wait.let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap();
("Mercury", 0.4),
("Venus", 0.7),
]);solar_distance.entry("Earth").or_insert(1.0);("Venus", 0.7),
let name1: Option = None;
// In this case, nothing will be printed out
if let Some(name) = name1 {
println!("{name}");
}
// In this case, nothing will be printed out
if let Some(name) = name1 {
println!("{name}");
}
let name2: Option = Some("Matthew");
// In this case, the word "Matthew" will be printed out
if let Some(name) = name2 {
println!("{name}");
}
}// In this case, the word "Matthew" will be printed out
if let Some(name) = name2 {
println!("{name}");
}
Pointers {| class"wikitable"Pointer (computer programming)>pointer and reference primitive types
!Type!Description!Examples- {{Rust|&T{edih}
- {{Rust|&mut T}}
}}
- {{Rust|let x_ref {{={edih} {{not a typo|&x;}}}}
- {{Rust|let x_ref {{=}} &mut x;}}
}}
- {{Rust|Option{edih}
- {{Rust|Option}}
}}
- Option wrapped reference
- Possibly null reference
{edih}
- {{Rust|None{edih}
- {{Rust|let x_ref {{=}} Some(&x);}}
- {{Rust|let x_ref {{=}} Some(&mut x);}}
}}
- {{Rust|Option}}}}|A pointer to heap-allocated value
- {{Rust|let boxed {{=}} Some(Box::new("Hello World"));}}}}
- {{Rust|const T{edih}
- {{Rust|mut T}}
}}
- Raw pointers (immutable and mutable)
- Possibly null; {{Rust|unsafe{edih} to dereference
}}
- {{Rust|let x_ptr {{={edih} &x as const T;}}
- {{Rust|let x_ptr {{=}} &mut x as mut T;}}
}}
User-defined types
User-defined types are created with the struct or enum keywords. The struct keyword is used to denote a record type that groups multiple related values.{{sfn|Klabnik|Nichols|2019|p=83}} enums can take on different variants at runtime, with its capabilities similar to algebraic data types found in functional programming languages.{{sfn|Klabnik|Nichols|2019|p=97}} Both structs and enums can contain fields with different types.{{sfn|Klabnik|Nichols|2019|pp=98â101}} Alternative names for the same type can be defined with the type keyword.{{sfn|Klabnik|Nichols|2019|pp=438â440}}The impl keyword can define methods for a user-defined type. Data and functions are defined separately. Implementations fulfill a role similar to that of classes within other languages.{{sfn|Klabnik|Nichols|2019|pp=93}}Type conversion
{{excerpt|Type conversion|Rust}}Ownership and lifetimes
Rust's ownership system consists of rules that ensure memory safety without using a garbage collector. At compile time, each value must be attached to a variable called the owner of that value, and every value must have exactly one owner.{{sfn|Klabnik|Nichols|2019|pp=59â61}} Values are moved between different owners through assignment or passing a value as a function parameter. Values can also be borrowed, meaning they are temporarily passed to a different function before being returned to the owner.{{sfn|Klabnik|Nichols|2019|pp=63â68}} With these rules, Rust can prevent the creation and use of dangling pointers:{{sfn|Klabnik|Nichols|2019|pp=63â68}}{{sfn|Klabnik|Nichols|2019|pp=74â75}}fn print_string(s: String) {
println!("{}", s);
}fn main() {
let s = String::from("Hello, World");
print_string(s); // s consumed by print_string
// s has been moved, so cannot be used any more
// another print_string(s); would result in a compile error
}Because of these ownership rules, Rust types are known as linear or affine types, meaning each value can be used exactly once. This enforces a form of software fault isolation as the owner of a value is solely responsible for its correctness and deallocation.BOOK, Balasubramanian, Abhiram, Baranowski, Marek S., Burtsev, Anton, Panda, Aurojit, RakamariÄ, Zvonimir, Ryzhyk, Leonid, Proceedings of the 16th Workshop on Hot Topics in Operating Systems, System Programming in Rust, 2017-05-07,weblink HotOS '17, New York, NY, US, Association for Computing Machinery, 156â161, 10.1145/3102980.3103006, 978-1-4503-5068-6, 24100599, June 1, 2022, June 11, 2022,weblink live, When a value goes out of scope, it is dropped by running its destructor. The destructor may be programmatically defined through implementing the {{code|Drop}} trait. This helps manage resources such as file handles, network sockets, and locks, since when objects are dropped, the resources associated with them are closed or released automatically.{{sfn|Klabnik|Nichols|2023|pp=327-30}}Lifetimes are usually an implicit part of all reference types in Rust. Each lifetime encompasses a set of locations in the code for which a variable is valid. For example, a reference to a local variable has a lifetime corresponding to the block it is defined in:{{sfn|Klabnik|Nichols|2019|p=194}}fn main() {
print_string(s); // s consumed by print_string
// s has been moved, so cannot be used any more
// another print_string(s); would result in a compile error
let x = 5; // ------------------+- Lifetime 'a
// |
let r = &x; // -+-- Lifetime 'b |
// | |
println!("r: {}", r); // | |
// | |
// -+ |
} // ------------------+The borrow checker in the Rust compiler uses lifetimes to ensure that the values a reference points to remain valid.{{sfn|Klabnik|Nichols|2019|pp=75,134}}WEB, Shamrell-Harrington, Nell, The Rust Borrow Checker â a Deep Dive,weblink 2022-06-25, InfoQ, en, In the example above, storing a reference to variable {{code|x}} to {{code|r}} is valid, as variable {{code|x}} has a longer lifetime ({{code|'a}}) than variable {{code|r}} ({{code|'b}}). However, when {{code|x}} has a shorter lifetime, the borrow checker would reject the program:fn main() {
// |
let r = &x; // -+-- Lifetime 'b |
// | |
println!("r: {}", r); // | |
// | |
// -+ |
let r; // ------------------+- Lifetime 'a
// |
{ // |
let x = 5; // -+-- Lifetime 'b |
r = &x; // | |
} // -| |
// |
println!("r: {}", r); // |
} // ------------------+Since the lifetime of the referenced variable ({{code|'b}}) is shorter than the lifetime of the variable holding the reference ({{code|'a}}), the borrow checker errors, preventing {{code|x}} from being used from outside its scope.{{sfn|Klabnik|Nichols|2019|pp=194-195}}Rust defines the relationship between the lifetimes of the objects created and used by functions, using lifetime parameters, as a signature feature.{{sfn|Klabnik|Nichols|2019|pp=192â204}}The example below parses some configuration options from a string and creates a struct containing the options. The struct only contains references to the data; so, for the struct to remain valid, the data referred to by the struct must be valid as well. The function signature for parse_config specifies this relationship explicitly. In this example, the explicit lifetimes are unnecessary in newer Rust versions, due to lifetime elision, which is an algorithm that automatically assigns lifetimes to functions if they are trivial.{{sfn|Klabnik|Nichols|2019|pp=201â203}}use std::collections::HashMap;// This struct has one lifetime parameter, 'src. The name is only used within the struct's definition. // |
{ // |
let x = 5; // -+-- Lifetime 'b |
r = &x; // | |
} // -| |
// |
println!("r: {}", r); // |
- [derive(Debug)]
- content above as imported from Wikipedia
- "Rust (programming language)" does not exist on GetWiki (yet)
- time: 5:00am EDT - Sat, May 18 2024
- "Rust (programming language)" does not exist on GetWiki (yet)
- time: 5:00am EDT - Sat, May 18 2024
[ this remote article is provided by Wikipedia ]
LATEST EDITS [ see all ]
GETWIKI 23 MAY 2022
The Illusion of Choice
Culture
Culture
GETWIKI 09 JUL 2019
Eastern Philosophy
History of Philosophy
History of Philosophy
GETWIKI 09 MAY 2016
GetMeta:About
GetWiki
GetWiki
GETWIKI 18 OCT 2015
M.R.M. Parrott
Biographies
Biographies
GETWIKI 20 AUG 2014
GetMeta:News
GetWiki
GetWiki
© 2024 M.R.M. PARROTT | ALL RIGHTS RESERVED