Product struct
- Go course
- Beginner
- Lesson 47/90
- 6 min
Define a struct representing a product.
Project: a shopping cart
In this project you will build a small program that adds products, computes the total and prints the cart neatly. The first step is modeling the data: each product has a name, a unit price and a quantity.
type Urun struct {
Ad string
Fiyat float64
Adet int
}
kalem := Urun{Ad: "Kalem", Fiyat: 12.5, Adet: 3}
fmt.Println(kalem.Ad, kalem.Fiyat*float64(kalem.Adet)) // Kalem 37.5A struct gathers related fields into a single value; the cart will be a slice of these values.
A subtotal method
Adding a method that computes the product's subtotal keeps the calculation in one place:
func (u Urun) AraToplam() float64 {
return u.Fiyat * float64(u.Adet)
}Because Adet is an int, it is converted to float64 before multiplying; Go doesn't mix different number types on its own.
Practice Product model
Write the Urun struct and the AraToplam() method. Print the subtotal for Urun{Ad: "Kalem", Fiyat: 12.5, Adet: 3}.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Urun struct {
Ad string
Fiyat float64
Adet int
}
func (u Urun) AraToplam() float64 {
return u.Fiyat * float64(u.Adet)
}
func main() {
k := Urun{Ad: "Kalem", Fiyat: 12.5, Adet: 3}
fmt.Println(k.AraToplam())
}Expected output
37.5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the advantage of naming fields (<code>Urun{Ad: ..., Fiyat: ...}</code>)?
- The code stays correct even if the order changes or fields are added Correct answer
- It runs faster
- It is required
- It uses less memory
Explanation: The unnamed form (Urun{"Kalem", 12.5, 3}) depends on field order; with named fields, omitted fields get their zero value.
2 Field access
u := Urun{Ad: "Defter", Fiyat: 20, Adet: 2}
fmt.Println(u____Ad)
u := Urun{Ad: "Defter", Fiyat: 20, Adet: 2}
fmt.Println(u.Ad)
Explanation: Struct fields are accessed with a dot.
3 Field and type
| Term | Meaning |
|---|---|
Ad |
string |
Fiyat |
float64 |
Adet |
int |
AraToplam() |
Returns float64 |