Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Problems
  • C
  • C++
  • Java
  • Python
  • JavaScript
  • Data Science
  • Machine Learning
  • Courses
  • Linux
  • DevOps
  • SQL
  • Web Development
  • System Design
  • Aptitude
  • GfG Premium
Open In App
Next Article:
Functions in Rust
Next article icon

Functions in Rust

Last Updated : 03 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Functions are the block of reusable code that can perform similar related actions. You have already seen one of the most important functions in the language: the main function, which is the entry point of many programs. You’ve also seen the "fn" keyword, which allows you to declare new functions. Rust code uses snake case as the conventional style for function and variable names. In snake case, all letters are lowercase and underscore separate words.

Syntax:

fn functionname(arguments){    code  }
  • To create a function we need to use the fn keyword.
  • The function name is written after the fn keyword
  • Arguments are passed after function name inside parenthesis
  • You can write function code in function block

Example:

We will look into a simple function in the below code

Rust
fn main() {     greet("kushwanthreddy"); }  fn greet(name: &str) {     println!("hello {} welcome to geeksforgeeks",name); } 

Output:

hello kushwanthreddy welcome to geeksforgeeks

In the above function declaration, we have written a greeting program that takes one argument and prints a welcome message. The parameter we have given to the greet function is a name(string datatype). We used the following approach:

  • The main function has a greet function
  • Greet function takes a name(string) as an argument
  • Greet function prints the welcome message
function in rust

Function Parameters

In the above example, we have used function without any arguments, arguments are the parameters that are special variables that are part of a function’s signature. Let us look into the below example which adds 2 numbers.

Rust
use std::io;  fn main() {     println!("enter a number:");     let mut stra = String::new();     io::stdin()         .read_line(&mut stra)         .expect("failed to read input.");     println!("enter b number:");     let mut strb = String::new();     io::stdin()         .read_line(&mut strb)         .expect("failed to read input.");      let a: i32 =  stra.trim().parse().expect("invalid input");     let b: i32 =  strb.trim().parse().expect("invalid input");      sum(a,b); }  fn sum(x: i32, y: i32) {     println!("sum = {}", x+y); } 

Output:

enter a number: 1  enter b number: 2    sum = 3

As above greet program in the above program, sum function in this program also takes 2 arguments which are generally integers and output is the sum of the integers given in the argument. Here we will use the below approach:

  • The program asks for input a
  • The program asks for input b
  • Sum program gets executed while taking a, b as arguments
  • Sum program prints the sum of a, b
function with arguments

Building a simple calculator in RUST

We will build a simple calculator using the function, function arguments, and conditional statements. For this we will use the below approach:

  • The program asks for number a
  • The program asks for number b
  • The program asks to choose what to do with numbers whether their sum, difference, product, or reminder
  • According to user input respective calculation is the calculator
  • The sum function calculates the sum
  • The sub function calculates the difference
  • The mul function calculates the product
  • The quo function finds out the quotient
  • The rem function finds out the remainder
  • For invalid argument program exits with a message "invalid"
Rust
use std::io; use std::process::exit;  fn main() {     println!("enter a number:");     let mut stra = String::new();     io::stdin()         .read_line(&mut stra)         .expect("failed to read input.");     println!("enter b number:");     let mut strb = String::new();     io::stdin()         .read_line(&mut strb)         .expect("failed to read input.");      let a: i32 =  stra.trim().parse().expect("invalid input");     let b: i32 =  strb.trim().parse().expect("invalid input");            println!("choose your calculation: \n1.sum              \n2.difference              \n3.product              \n4.quotient              \n5.remainder\n");                     let mut choose = String::new();     io::stdin()         .read_line(&mut choose)         .expect("failed to read input.");     let c: i32 =  choose.trim().parse().expect("invalid input");        // Select Operation using conditionals       if c==1{sum(a,b);}       else if c==2{sub(a,b);}       else if c==3{mul(a,b);}       else if c==4{quo(a,b);}       else if c==5{rem(a,b);}       else{println!("Invalid argument");exit(1);} }  // Sum function fn sum(x: i32, y: i32) {     println!("sum = {}", x+y); }  // Difference function fn sub(x: i32, y: i32) {     println!("difference = {}", x-y); }  // Product function fn mul(x: i32, y: i32) {     println!("product = {}", x*y); }  // Division function fn quo(x: i32, y: i32) {     println!("quotient = {}", x/y); }  // Remainder function fn rem(x: i32, y: i32) {     println!("remainder = {}", x%y); } 

Output:

enter a number:                                                      2                                                                    enter b number:                                                      4                                                                    choose your calculation:                                             1.sum                                                                2.difference                                                         3.product                                                            4.quotient                                                           5.remainder                                                                                                                               3                                                                    product = 8

Next Article
Functions in Rust

K

kushwanthreddy
Improve
Article Tags :
  • Programming Language
  • Rust
  • Rust functions

Similar Reads

    Rust - Generic Function
    In Rust, Generic functions are very useful. Generic make code more flexible and provide more functionality to the callers of the function. It prevents code duplication as it is not required to define different functions of different types. Generics are specified in the signature of function where we
    3 min read
    Conditionals in Rust
    Conditional Statements are the decision-making statements based on given conditions. Conditional statements are common in programming languages and rust has them and unlike many of them, the boolean condition doesn't need to be surrounded by parentheses but is better to use, and each condition is fo
    3 min read
    JS++ | Functions
    A function is a section of code which contains a set of instructions, where the instructions describe how a particular task is to be accomplished. Functions are declared and may then be called one or more times. Declaring a function involves specifying the instructions that the function will contain
    10 min read
    Rust - Higher Order Functions
    In Rust, we have a concept of Higher order functions that passes the function to another function once the variable is stored in another function. To define a function in Rust, we use the fn keyword. Syntax: fn <function name>() { } Higher-order functions in Rust are those functions that take
    2 min read
    Rust - Diverging Functions
    In Rust, we have a concept of diverging functions. Diverging functions are unique function that returns neither value nor anything else. For declaring a function as diverging, we use a keyword named panic! that is a macro in Rust (similar to println! macro). While println! macro is responsible for f
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences