Tuesday, April 19, 2022

Go vs Rust - Struct

1 A structure or struct is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming. It can be termed as a lightweight class that does not support inheritance but supports composition.

Go

type Address struct {
    name, city string
    Pincode int
}

// Declaring a variable of a `struct` type. All the struct fields are initialized with their zero value
var a Address 
fmt.Println(a)

// Declaring and initializing a struct using a struct literal
a1 := Address{"Akshay", "Dehradun", 3623572}

// Naming fields while initializing a struct
a2 := Address{Name: "Anikaa", city: "Ballia", Pincode: 277001}

// Pointers to a struct by &. Uninitialized fields are set to their corresponding zero-value
a3 := &Address{Name: "Delhi"}
fmt.Println("Address3: ", (*a3).Name)
fmt.Println("Address3: ", a3.Name)

Anonymous Structure

    // Creating and initializing the anonymous structure
    Element := struct {
        name      string
        branch    string
        language  string
        Particles int
    }{
        name:      "Pikachu",
        branch:    "ECE",
        language:  "C++",
        Particles: 498,
    }

Anonymous Fields 
It's like Tuple Struct in Rust. but not allowed the same data type in Go.

// Creating a structure with anonymous fields
type student struct {
    int
    string
    float64
}

    // Assigning values to the anonymous fields of the student structure
    value := student{123, "Bud", 8900.23}
  
    // Display the values of the fields
    fmt.Println("Enrollment number : ", value.int)
    fmt.Println("Student name : ", value.string)
    fmt.Println("Package price : ", value.float64)

Rust

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
}

// A unit struct
struct Unit;

// A tuple struct
struct Pair(i32, f32);

// A struct with two fields
struct Point {
    x: f32,
    y: f32,
}

// Structs can be reused as fields of another struct
#[allow(dead_code)]
struct Rectangle {
    top_left: Point,
    bottom_right: Point,
}

    // Create struct with field init shorthand
    let name = String::from("Peter");
    let age = 27;
    let peter = Person { name, age };

    // Print debug struct
    println!("{:?}", peter);

    // Instantiate a `Point`
    let point: Point = Point { x: 10.3, y: 0.4 };

    // Access the fields of the point
    println!("point coordinates: ({}, {})", point.x, point.y);

    // Make a new point by using struct update syntax to use the fields of our
    // other one
    let bottom_right = Point { x: 5.2, ..point };

    // `bottom_right.y` will be the same as `point.y` because we used that field
    // from `point`
    println!("second point: ({}, {})", bottom_right.x, bottom_right.y);

    // Destructure the point using a `let` binding
    let Point { x: left_edge, y: top_edge } = point;

    let _rectangle = Rectangle {
        // struct instantiation is an expression too
        top_left: Point { x: left_edge, y: top_edge },
        bottom_right: bottom_right,
    };

    // Instantiate a unit struct
    let _unit = Unit;

    // Instantiate a tuple struct
    let pair = Pair(1, 0.1);

    // Access the fields of a tuple struct
    println!("pair contains {:?} and {:?}", pair.0, pair.1);

    // Destructure a tuple struct
    let Pair(integer, decimal) = pair;

    println!("pair contains {:?} and {:?}", integer, decimal);

2 Inheritance
Prefer Composition to Inheritance. Both Go and Rust has no inheritance concept.

Go
Base structs can be embedded into a child struct and the methods of the base struct can be directly called on the child struct.

// Golang program to illustrate the concept of multiple inheritances
package main
  
import (
    "fmt"
)
  
// declaring first base struct 
type first struct{
    base_one string
}
  
// declaring second base struct
type second struct{
    base_two string
}
  
// function to return first struct variable
func (f first) printBase1() string{      
    return f.base_one
}
  
// function to return second struct variable
func (s second) printBase2() string{
    return s.base_two
}
  
// child struct which embeds both base structs
type child struct{
    // anonymous fields, struct embedding of multiple structs
    first
    second
}
  
// main function
func main() {
      
    // declaring an instance of child struct
    c1 := child{   
        // child struct can directly access base struct variables
        first{    
            base_one: "In base struct 1.",
        },
        second{
            base_two: "\nIn base struct 2.\n",
        },
    }
      
    // child struct can directly access base struct methods
    // printing base method using instance of child struct
    fmt.Println(c1.printBase1())
    fmt.Println(c1.printBase2())
}

Rust

struct MyStruct {
    name: String
}

struct Pair(MyStruct, f32);

fn main() {       
    let pair = Pair(MyStruct{name: String::from("bq")}, 0.1);
    println!("hello world {}", pair.0.name);
}

No comments:

Post a Comment