rust language pub keyword syntax
In rust, pub is a keyword that specifies the visibility of an item. It can be used to control the visibility of functions, structures, enums, constants, traits, etc. in modules.
If an item is marked as pub, it can be accessed and used by external modules. If an item is not marked as pub, it can only be accessed inside the current module.
// Module definitionmod foo { // Function definition, no tag pub fn private_function() { println!("This is a private function."); } // Function definition, tag pub pub fn public_function() { println!("This is a public function."); } // Structure definition, tag pub pub struct PublicStruct { pub field1: i32, field2: i32, } // Enumeration definition, tag pub pub enum PublicEnum { Option1, Option2, } } // Use common functions and structures in foo module in another modulefn main() { foo::public_function(); // You can call public functions let my_struct = foo::PublicStruct { field1: 42, field2: 13 }; // Can create instances of public structures // Compilation error: private_function is a private function and cannot be accessed // foo::private_function(); }
Some in Rust
1. First of all, you need to know what Option and Result are
source:
Many languages use the null/nil/undefined type to represent empty output and handle exception errors. Rust skipped, especially to prevent problems such as null pointer exceptions, sensitive data leakage due to exceptions and other reasons, etc. Instead, Rust provides two special class enumerations: Option and Result are used to deal with the above problems.
content:
- The optional value is either Some or None
Result is either successful/Ok or failed/Err
// An output can have either Some value or no value/ None. enum Option<T> { // T is a generic and it can contain any type of value. Some(T), None, } // A result can represent either success/ Ok or failure/ Err. enum Result<T, E> { // T and E are generics. T can contain any type of value, E can be any error. Ok(T), Err(E), }
And there is no need to introduce them separately
Basic usage of Option:
When writing a function or data type:
- If the parameters of a function are optional
- If the function is non-empty and the output returns may not be empty
- If a value, the data type of the property that is alive may be empty
2. We have to use Option as their data type
For example, the output of a function may be of type &str or the output is empty, and the return type of the function may be set to Option<&str>
fn get_an_optional_value() -> Option<&str> { //if the optional value is not empty return Some("Some value"); //else None }
struct Name { first_name: String, middle_name: Option<String>, // middle_name can be empty last_name: String, }
The above is the detailed content of the basic pub keywords and some syntax examples of the rust language. For more information about the rust language pub Some syntax, please follow my other related articles!