Author: Saim Khalid

  • Variables

    In MATLAB environment, every variable is an array or matrix.

    You can assign variables in a simple way. For example,

    x = 3	       % defining x and initializing it with a value

    MATLAB will execute the above statement and return the following result −

    x = 3
    

    It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check another example,

    x = sqrt(16) 	% defining x and initializing it with an expression

    MATLAB will execute the above statement and return the following result −

    x = 4
    

    Please note that −

    • Once a variable is entered into the system, you can refer to it later.
    • Variables must have values before they are used.
    • When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later.

    For example,

    sqrt(78)

    MATLAB will execute the above statement and return the following result −

    ans =  8.8318
    

    You can use this variable ans −

    sqrt(78);
    9876/ans

    MATLAB will execute the above statement and return the following result −

    ans =  1118.2
    

    Let’s look at another example −

    x = 7 * 8;
    y = x * 7.89

    MATLAB will execute the above statement and return the following result −

    y =  441.84
    

    Multiple Assignments

    You can have multiple assignments on the same line. For example,

    a = 2; b = 7; c = a * b

    MATLAB will execute the above statement and return the following result −

    c = 14
    

    I have forgotten the Variables!

    The who command displays all the variable names you have used.

    who
    

    MATLAB will execute the above statement and return the following result −

    Your variables are:
    a    ans  b    c   
    

    The whos command displays little more about the variables −

    • Variables currently in memory
    • Type of each variables
    • Memory allocated to each variable
    • Whether they are complex variables or not
    whos
    

    MATLAB will execute the above statement and return the following result −

    Attr Name        Size        Bytes      Class
    ==== ====        ====        ====       ===== 
       a             1x1           8        double
       ans           1x70         757        cell
       b             1x1           8        double
       c             1x1           8        double
    
    Total is 73 elements using 781 bytes     
    

    The clear command deletes all (or the specified) variable(s) from the memory.

    clear x     % it will delete x, won't display anything
    clear       % it will delete all variables in the workspace
    
            %  peacefully and unobtrusively 

    Long Assignments

    Long assignments can be extended to another line by using an ellipses (…). For example,

    initial_velocity = 0;
    acceleration = 9.8;
    time = 20;
    final_velocity = initial_velocity + acceleration * time

    MATLAB will execute the above statement and return the following result −

    final_velocity = 196
    

    The format Command

    By default, MATLAB displays numbers with four decimal place values. This is known as short format.

    However, if you want more precision, you need to use the format command.

    The format long command displays 16 digits after decimal.

    For example −

    format long
    x = 7 + 10/3 + 5 ^ 1.2

    MATLAB will execute the above statement and return the following result−

    x = 17.2319816406394
    

    Another example,

    format short
    x = 7 + 10/3 + 5 ^ 1.2

    MATLAB will execute the above statement and return the following result −

    x = 17.232
    

    The format bank command rounds numbers to two decimal places. For example,

    format bank
    daily_wage = 177.45;
    weekly_wage = daily_wage * 6

    MATLAB will execute the above statement and return the following result −

    weekly_wage = 1064.70
    

    MATLAB displays large numbers using exponential notation.

    The format short e command allows displaying in exponential form with four decimal places plus the exponent.

    For example,

    format short e
    4.678 * 4.9

    MATLAB will execute the above statement and return the following result −

    ans = 2.2922e+01
    

    The format long e command allows displaying in exponential form with four decimal places plus the exponent. For example,

    format long e
    x = pi

    MATLAB will execute the above statement and return the following result −

    x = 3.141592653589793e+00
    

    The format rat command gives the closest rational expression resulting from a calculation. For example,

    format rat
    4.678 * 4.9

    MATLAB will execute the above statement and return the following result −

    ans = 34177/1491 
    

    Creating Vectors

    A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −

    • Row vectors
    • Column vectors

    Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements.

    For example,

    r = [7 8 9 10 11]

    MATLAB will execute the above statement and return the following result −

    r =
    
       7    8    9   10   11 
    

    Another example,

    r = [7 8 9 10 11];
    t = [2, 3, 4, 5, 6];
    res = r + t

    MATLAB will execute the above statement and return the following result −

    res =
    
    
         9         11         13         15         17

    Column vectors are created by enclosing the set of elements in square brackets, using semicolon(;) to delimit the elements.

    c = [7;  8;  9;  10; 11]

    MATLAB will execute the above statement and return the following result −

    c =
    
       7       
       8       
       9       
      10       
      11  

    Creating Matrices

    A matrix is a two-dimensional array of numbers.

    In MATLAB, a matrix is created by entering each row as a sequence of space or comma separated elements, and end of a row is demarcated by a semicolon. For example, let us create a 3-by-3 matrix as −

    m = [1 2 3; 4 5 6; 7 8 9]

    MATLAB will execute the above statement and return the following result −

    m =
    
       1              2              3       
       4              5              6       
       7              8              9       </code></pre>
  • Basic Syntax

    MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command prompt.

    MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right away.

    Hands on Practice

    Type a valid expression, for example,

    5 + 5

    And press ENTER

    When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −

    ans = 10
    

    Let us take up few more examples −

    3 ^ 2	       % 3 raised to the power of 2

    When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −

    ans = 9
    

    Another example,

    sin(pi /2)	  % sine of angle 90o
    

    When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −

    ans = 1
    

    Another example,

    7/0		      % Divide by zero

    When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −

    ans = Inf
    warning: division by zero
    

    Another example,

    732 * 20.3	

    When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −

    ans =  1.4860e+04
    

    MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for ‘not a number’.

    Use of Semicolon (;) in MATLAB

    Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for an expression, add a semicolon after the expression.

    For example,

    x = 3;
    y = x + 5

    When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −

    y =  8
    

    Adding Comments

    The percent symbol (%) is used for indicating a comment line. For example,

    x = 9	     % assign the value 9 to x

    You can also write a block of comments using the block comment operators % { and % }.

    The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments.

    Commonly used Operators and Special Characters

    MATLAB supports the following commonly used operators and special characters −

    OperatorPurpose
    +Plus; addition operator.
    Minus; subtraction operator.
    *Scalar and matrix multiplication operator.
    .*Array multiplication operator.
    ^Scalar and matrix exponentiation operator.
    .^Array exponentiation operator.
    \Left-division operator.
    /Right-division operator.
    .\Array left-division operator.
    ./Array right-division operator.
    :Colon; generates regularly spaced elements and represents an entire row or column.
    ( )Parentheses; encloses function arguments and array indices; overrides precedence.
    [ ]Brackets; enclosures array elements.
    .Decimal point.
    Ellipsis; line-continuation operator
    ,Comma; separates statements and elements in a row
    ;Semicolon; separates columns and suppresses display.
    %Percent sign; designates a comment and specifies formatting.
    _Quote sign and transpose operator.
    ._Nonconjugated transpose operator.
    =Assignment operator.

    Special Variables and Constants

    MATLAB supports the following special variables and constants −

    NameMeaning
    ansMost recent answer.
    epsAccuracy of floating-point precision.
    i,jThe imaginary unit √-1.
    InfInfinity.
    NaNUndefined numerical result (not a number).
    piThe number π

    Naming Variables

    Variable names consist of a letter followed by any number of letters, digits or underscore.

    MATLAB is case-sensitive.

    Variable names can be of any length, however, MATLAB uses only first N characters, where N is given by the function namelengthmax.

    Saving Your Work

    The save command is used for saving all the variables in the workspace, as a file with .mat extension, in the current directory.

    For example,

    save myfile
    

    You can reload the file anytime later using the load command.

    load myfile
    
  • Environment Setup

    Local Environment Setup

    Setting up MATLAB environment is a matter of few clicks. The installer can be downloaded from here.

    MathWorks provides the licensed product, a trial version and a student version as well. You need to log into the site and wait a little for their approval.

    After downloading the installer the software can be installed through few clicks.

    Online Installation of MATLAB
    Installing

    Understanding the MATLAB Environment

    MATLAB development IDE can be launched from the icon created on the desktop. The main working window in MATLAB is called the desktop. When MATLAB is started, the desktop appears in its default layout −

    MATLAB desktop

    The desktop has the following panels −

    • Current Folder − This panel allows you to access the project folders and files.
    Current Folder
    • Command Window − This is the main area where commands can be entered at the command line. It is indicated by the command prompt (>>).
    Command Window
    • Workspace − The workspace shows all the variables created and/or imported from files.
    Workspace
    • Command History − This panel shows or return commands that are entered at the command line.
    Command History

    Set up GNU Octave

    If you are willing to use Octave on your machine ( Linux, BSD, OS X or Windows ), then kindly download latest version from Download GNU Octave. You can check the given installation instructions for your machine.

  • Overview

    MATLAB (matrix laboratory) is a fourth-generation high-level programming language and interactive environment for numerical computation, visualization and programming.

    MATLAB is developed by MathWorks.

    It allows matrix manipulations; plotting of functions and data; implementation of algorithms; creation of user interfaces; interfacing with programs written in other languages, including C, C++, Java, and FORTRAN; analyze data; develop algorithms; and create models and applications.

    It has numerous built-in commands and math functions that help you in mathematical calculations, generating plots, and performing numerical methods.

    MATLAB’s Power of Computational Mathematics

    MATLAB is used in every facet of computational mathematics. Following are some commonly used mathematical calculations where it is used most commonly −

    • Dealing with Matrices and Arrays
    • 2-D and 3-D Plotting and graphics
    • Linear Algebra
    • Algebraic Equations
    • Non-linear Functions
    • Statistics
    • Data Analysis
    • Calculus and Differential Equations
    • Numerical Calculations
    • Integration
    • Transforms
    • Curve Fitting
    • Various other special functions

    Features of MATLAB

    Following are the basic features of MATLAB −

    • It is a high-level language for numerical computation, visualization and application development.
    • It also provides an interactive environment for iterative exploration, design and problem solving.
    • It provides vast library of mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, numerical integration and solving ordinary differential equations.
    • It provides built-in graphics for visualizing data and tools for creating custom plots.
    • MATLAB’s programming interface gives development tools for improving code quality maintainability and maximizing performance.
    • It provides tools for building applications with custom graphical interfaces.
    • It provides functions for integrating MATLAB based algorithms with external applications and languages such as C, Java, .NET and Microsoft Excel.

    Uses of MATLAB

    MATLAB is widely used as a computational tool in science and engineering encompassing the fields of physics, chemistry, math and all engineering streams. It is used in a range of applications including −

    • Signal Processing and Communications
    • Image and Video Processing
    • Control Systems
    • Test and Measurement
    • Computational Finance
    • Computational Biology
  • Error Handling

    Go programming provides a pretty simple error handling framework with inbuilt error interface type of the following declaration −

    type error interface {
       Error() string
    }
    

    Functions normally return error as last return value. Use errors.New to construct a basic error message as following −

    func Sqrt(value float64)(float64, error) {
       if(value < 0){
    
      return 0, errors.New("Math: negative number passed to Sqrt")
    } return math.Sqrt(value), nil }

    Use return value and error message.

    result, err:= Sqrt(-1)
    
    if err != nil {
       fmt.Println(err)
    }

    Example

    Live Demo

    package main
    
    import "errors"
    import "fmt"
    import "math"
    
    func Sqrt(value float64)(float64, error) {
       if(value < 0){
    
      return 0, errors.New("Math: negative number passed to Sqrt")
    } return math.Sqrt(value), nil } func main() { result, err:= Sqrt(-1) if err != nil {
      fmt.Println(err)
    } else {
      fmt.Println(result)
    } result, err = Sqrt(9) if err != nil {
      fmt.Println(err)
    } else {
      fmt.Println(result)
    } }

    When the above code is compiled and executed, it produces the following result −

    Math: negative number passed to Sqrt
    3
    
  • Interfaces

    Go programming provides another data type called interfaces which represents a set of method signatures. The struct data type implements these interfaces to have method definitions for the method signature of the interfaces.

    Syntax

    /* define an interface */
    type interface_name interface {
       method_name1 [return_type]
       method_name2 [return_type]
       method_name3 [return_type]
       ...
       method_namen [return_type]
    }
    
    /* define a struct */
    type struct_name struct {
       /* variables */
    }
    
    /* implement interface methods*/
    func (struct_name_variable struct_name) method_name1() [return_type] {
       /* method implementation */
    }
    ...
    func (struct_name_variable struct_name) method_namen() [return_type] {
       /* method implementation */
    }
    

    Example

    Live Demo

    package main
    
    import ("fmt" "math")
    
    /* define an interface */
    type Shape interface {
       area() float64
    }
    
    /* define a circle */
    type Circle struct {
       x,y,radius float64
    }
    
    /* define a rectangle */
    type Rectangle struct {
       width, height float64
    }
    
    /* define a method for circle (implementation of Shape.area())*/
    func(circle Circle) area() float64 {
       return math.Pi * circle.radius * circle.radius
    }
    
    /* define a method for rectangle (implementation of Shape.area())*/
    func(rect Rectangle) area() float64 {
       return rect.width * rect.height
    }
    
    /* define a method for shape */
    func getArea(shape Shape) float64 {
       return shape.area()
    }
    
    func main() {
       circle := Circle{x:0,y:0,radius:5}
       rectangle := Rectangle {width:10, height:5}
       
       fmt.Printf("Circle area: %f\n",getArea(circle))
       fmt.Printf("Rectangle area: %f\n",getArea(rectangle))
    }

    When the above code is compiled and executed, it produces the following result −

    Circle area: 78.539816
    Rectangle area: 50.000000
    
  • Recursion

    Recursion is the process of repeating items in a self-similar way. The same concept applies in programming languages as well. If a program allows to call a function inside the same function, then it is called a recursive function call. Take a look at the following example −

    func recursion() {
       recursion() /* function calls itself */
    }
    func main() {
       recursion()
    }

    The Go programming language supports recursion. That is, it allows a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go on to become an infinite loop.

    Examples of Recursion in Go

    Recursive functions are very useful to solve many mathematical problems such as calculating factorial of a number, generating a Fibonacci series, etc.

    Example 1: Calculating Factorial Using Recursion in Go

    The following example calculates the factorial of a given number using a recursive function −

    package main
    
    import "fmt"
    
    func factorial(i int)int {
       if(i <= 1) {
    
      return 1
    } return i * factorial(i - 1) } func main() { var i int = 15 fmt.Printf("Factorial of %d is %d", i, factorial(i)) }

    When the above code is compiled and executed, it produces the following result −

    Factorial of 15 is 1307674368000
    

    Example 2: Fibonacci Series Using Recursion in Go

    The following example shows how to generate a Fibonacci series of a given number using a recursive function

    package main
    
    import "fmt"
    
    func fibonaci(i int) (ret int) {
       if i == 0 {
    
      return 0
    } if i == 1 {
      return 1
    } return fibonaci(i-1) + fibonaci(i-2) } func main() { var i int for i = 0; i < 10; i++ {
      fmt.Printf("%d ", fibonaci(i))
    } }

    When the above code is compiled and executed, it produces the following result −

    0 1 1 2 3 5 8 13 21 34 
    
  • Maps

    Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.

    Defining a Map

    You must use make function to create a map.

    /* declare a variable, by default map will be nil*/
    var map_variable map[key_data_type]value_data_type
    
    /* define the map as nil map can not be assigned any value*/
    map_variable = make(map[key_data_type]value_data_type)
    

    Example

    The following example illustrates how to create and use a map −

    package main
    
    import "fmt"
    
    func main() {
       var countryCapitalMap map[string]string
       /* create a map*/
       countryCapitalMap = make(map[string]string)
       
       /* insert key-value pairs in the map*/
       countryCapitalMap["France"] = "Paris"
       countryCapitalMap["Italy"] = "Rome"
       countryCapitalMap["Japan"] = "Tokyo"
       countryCapitalMap["India"] = "New Delhi"
       
       /* print map using keys*/
       for country := range countryCapitalMap {
    
      fmt.Println("Capital of",country,"is",countryCapitalMap&#91;country])
    } /* test if entry is present in the map or not*/ capital, ok := countryCapitalMap["United States"] /* if ok is true, entry is present otherwise entry is absent*/ if(ok){
      fmt.Println("Capital of United States is", capital)  
    } else {
      fmt.Println("Capital of United States is not present") 
    } }

    When the above code is compiled and executed, it produces the following result −

    Capital of India is New Delhi
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    Capital of United States is not present
    

    delete() Function

    delete() function is used to delete an entry from a map. It requires the map and the corresponding key which is to be deleted. For example −

    package main
    
    import "fmt"
    
    func main() {   
       /* create a map*/
       countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
       
       fmt.Println("Original map")   
       
       /* print map */
       for country := range countryCapitalMap {
    
      fmt.Println("Capital of",country,"is",countryCapitalMap&#91;country])
    } /* delete an entry */ delete(countryCapitalMap,"France"); fmt.Println("Entry for France is deleted") fmt.Println("Updated map") /* print map */ for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap&#91;country])
    } }

    When the above code is compiled and executed, it produces the following result −

    Original Map
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    Capital of India is New Delhi
    Entry for France is deleted
    Updated Map
    Capital of India is New Delhi
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    
  • Range

    The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table.

    Range expression1st Value2nd Value(Optional)
    Array or slice a [n]Eindex i inta[i] E
    String s string typeindex i intrune int
    map m map[K]Vkey k Kvalue m[k] V
    channel c chan Eelement e Enone

    Example

    The following paragraph shows how to use range −

    package main
    
    import "fmt"
    
    func main() {
       /* create a slice */
       numbers := []int{0,1,2,3,4,5,6,7,8} 
       
       /* print the numbers */
       for i:= range numbers {
    
      fmt.Println("Slice item",i,"is",numbers&#91;i])
    } /* create a map*/ countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"} /* print map using keys*/ for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap&#91;country])
    } /* print map using key-value*/ for country,capital := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",capital)
    } }

    When the above code is compiled and executed, it produces the following result −

    Slice item 0 is 0
    Slice item 1 is 1
    Slice item 2 is 2
    Slice item 3 is 3
    Slice item 4 is 4
    Slice item 5 is 5
    Slice item 6 is 6
    Slice item 7 is 7
    Slice item 8 is 8
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    Capital of France is Paris
    Capital of Italy is Rome
    Capital of Japan is Tokyo
    
  • Structures

    Go arrays allow you to define variables that can hold several data items of the same kind. Structure is another user-defined data type available in Go programming, which allows you to combine data items of different kinds.

    Structures are used to represent a record. Suppose you want to keep track of the books in a library. You might want to track the following attributes of each book −

    • Title
    • Author
    • Subject
    • Book ID

    In such a scenario, structures are highly useful.

    Defining a Structure

    To define a structure, you must use type and struct statements. The struct statement defines a new data type, with multiple members for your program. The type statement binds a name with the type which is struct in our case. The format of the struct statement is as follows −

    type struct_variable_type struct {
       member definition;
       member definition;
       ...
       member definition;
    }

    Once a structure type is defined, it can be used to declare variables of that type using the following syntax.

    variable_name := structure_variable_type {value1, value2...valuen}
    

    Accessing Structure Members

    To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. The following example explains how to use a structure −

    package main
    
    import "fmt"
    
    type Books struct {
       title string
       author string
       subject string
       book_id int
    }
    func main() {
       var Book1 Books    /* Declare Book1 of type Book */
       var Book2 Books    /* Declare Book2 of type Book */
     
       /* book 1 specification */
       Book1.title = "Go Programming"
       Book1.author = "Mahesh Kumar"
       Book1.subject = "Go Programming Tutorial"
       Book1.book_id = 6495407
    
       /* book 2 specification */
       Book2.title = "Telecom Billing"
       Book2.author = "Zara Ali"
       Book2.subject = "Telecom Billing Tutorial"
       Book2.book_id = 6495700
     
       /* print Book1 info */
       fmt.Printf( "Book 1 title : %s\n", Book1.title)
       fmt.Printf( "Book 1 author : %s\n", Book1.author)
       fmt.Printf( "Book 1 subject : %s\n", Book1.subject)
       fmt.Printf( "Book 1 book_id : %d\n", Book1.book_id)
    
       /* print Book2 info */
       fmt.Printf( "Book 2 title : %s\n", Book2.title)
       fmt.Printf( "Book 2 author : %s\n", Book2.author)
       fmt.Printf( "Book 2 subject : %s\n", Book2.subject)
       fmt.Printf( "Book 2 book_id : %d\n", Book2.book_id)
    }

    When the above code is compiled and executed, it produces the following result −

    Book 1 title      : Go Programming
    Book 1 author     : Mahesh Kumar
    Book 1 subject    : Go Programming Tutorial
    Book 1 book_id    : 6495407
    Book 2 title      : Telecom Billing
    Book 2 author     : Zara Ali
    Book 2 subject    : Telecom Billing Tutorial
    Book 2 book_id    : 6495700
    

    Structures as Function Arguments

    You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the same way as you did in the above example −

    package main
    
    import "fmt"
    
    type Books struct {
       title string
       author string
       subject string
       book_id int
    }
    func main() {
       var Book1 Books    /* Declare Book1 of type Book */
       var Book2 Books    /* Declare Book2 of type Book */
     
       /* book 1 specification */
       Book1.title = "Go Programming"
       Book1.author = "Mahesh Kumar"
       Book1.subject = "Go Programming Tutorial"
       Book1.book_id = 6495407
    
       /* book 2 specification */
       Book2.title = "Telecom Billing"
       Book2.author = "Zara Ali"
       Book2.subject = "Telecom Billing Tutorial"
       Book2.book_id = 6495700
     
       /* print Book1 info */
       printBook(Book1)
    
       /* print Book2 info */
       printBook(Book2)
    }
    func printBook( book Books ) {
       fmt.Printf( "Book title : %s\n", book.title);
       fmt.Printf( "Book author : %s\n", book.author);
       fmt.Printf( "Book subject : %s\n", book.subject);
       fmt.Printf( "Book book_id : %d\n", book.book_id);
    }

    When the above code is compiled and executed, it produces the following result −

    Book title     : Go Programming
    Book author    : Mahesh Kumar
    Book subject   : Go Programming Tutorial
    Book book_id   : 6495407
    Book title     : Telecom Billing
    Book author    : Zara Ali
    Book subject   : Telecom Billing Tutorial
    Book book_id   : 6495700
    

    Pointers to Structures

    You can define pointers to structures in the same way as you define pointer to any other variable as follows −

    var struct_pointer *Books
    

    Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure’s name as follows −

    struct_pointer = &Book1;
    

    To access the members of a structure using a pointer to that structure, you must use the “.” operator as follows −

    struct_pointer.title;
    

    Let us re-write the above example using structure pointer −

    package main
    
    import "fmt"
    
    type Books struct {
       title string
       author string
       subject string
       book_id int
    }
    func main() {
       var Book1 Books   /* Declare Book1 of type Book */
       var Book2 Books   /* Declare Book2 of type Book */
     
       /* book 1 specification */
       Book1.title = "Go Programming"
       Book1.author = "Mahesh Kumar"
       Book1.subject = "Go Programming Tutorial"
       Book1.book_id = 6495407
    
       /* book 2 specification */
       Book2.title = "Telecom Billing"
       Book2.author = "Zara Ali"
       Book2.subject = "Telecom Billing Tutorial"
       Book2.book_id = 6495700
     
       /* print Book1 info */
       printBook(&Book1)
    
       /* print Book2 info */
       printBook(&Book2)
    }
    func printBook( book *Books ) {
       fmt.Printf( "Book title : %s\n", book.title);
       fmt.Printf( "Book author : %s\n", book.author);
       fmt.Printf( "Book subject : %s\n", book.subject);
       fmt.Printf( "Book book_id : %d\n", book.book_id);
    }

    When the above code is compiled and executed, it produces the following result −

    Book title     : Go Programming
    Book author    : Mahesh Kumar
    Book subject   : Go Programming Tutorial
    Book book_id   : 6495407
    Book title     : Telecom Billing
    Book author    : Zara Ali
    Book subject   : Telecom Billing Tutorial
    Book book_id   : 6495700