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 rustFunction 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 argumentsBuilding 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
Similar Reads
Introduction of Object Oriented Programming As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functi
6 min read
R Programming Language - Introduction R is a programming language and software environment that has become the first choice for statistical computing and data analysis. Developed in the early 1990s by Ross Ihaka and Robert Gentleman, R was built to simplify complex data manipulation and create clear, customizable visualizations. Over ti
4 min read
Features of C Programming Language C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system.The main features of C language include low-level access to memory, a simple set of keywords, and a clean style
3 min read
Introduction to Programming Languages Introduction: A programming language is a set of instructions and syntax used to create software programs. Some of the key features of programming languages include: Syntax: The specific rules and structure used to write code in a programming language.Data Types: The type of values that can be store
13 min read
Difference between Shallow and Deep copy of a class Shallow Copy: Shallow repetition is quicker. However, it's "lazy" it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each of the first and therefore the copy can have pointers th
5 min read
Go Tutorial Go or you say Golang is a procedural and statically typed programming language having the syntax similar to C programming language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language and mainly used in Google
2 min read
Structures in C++ C++ Structures are used to create user defined data types which are used to store group of items of different data types.SyntaxBefore using structure, we have to first define the structure using the struct keyword as shown:C++struct name{ type1 mem1; type2 mem2; ... };where structure name is name an
8 min read
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
type() function in Python The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
5 min read
Top 20 Programming Languages to Learn [2025 Updated] Whether you're starting your coding journey, upskilling, or want to make a career in artificial intelligence, data science in this rapidly evolving tech world, staying ahead requires mastering the right programming language in 2025. The top programming langauges include Python, JavaScript, Java, C#,
15 min read