Changing slice value in struct

Hi everyone, as you could see from the code i am beginner hobbiest trying to learn go. i need help on changing slice value. thank you all

package main

import (
	"fmt"
	"os"
	"os/exec"
	"time"
)

type Human struct {
	Name    string
	Health  int
	Weapon  []string
	PowerUp int
}

func main() {
	for i := 0; i < 3; i++ {
		fmt.Println("______go_game_______")
	}
	time.Sleep(1 * time.Second)
	clear()
	fmt.Println("Enter Hero's Name")
	var name string
	fmt.Scan(&name)
	player := CreateHuman(name)

	fmt.Println(player.Health)

	Trll := CreateMonster("Troll")
	fmt.Println(Trll.Weapon)
	Trll.Health = 60
	fmt.Println(Trll.Weapon[Bow.Damage])
       // change slice value
	bowd := Trll.Weapon[0]
	fmt.Println(bowd)

}

// CreateHuman creates human struct
func CreateHuman(name string) Human {
	return Human{Name: name, Health: 100, PowerUp: 0, Weapon: []string{"bow", "hammer"}}
}

func clear() {
	cmd := exec.Command("clear")
	cmd.Stdout = os.Stdout
	cmd.Run()
}

// monster file

type Weapons struct {
	Damage int
}

type Monster struct {
	Name   string
	Health int
	Weapon []Weapons
}

var Bow, Sword, Hammer Weapons

// CreateMonster ...
func CreateMonster(name string) Monster {

	return Monster{
		Name:   name,
		Health: 100,
		Weapon: []Weapons{
			Bow,
			Sword,
			Hammer,
		},
	}
} 

What slice value do you want to change? What do you want to change it to?

thank you for the response,
i want to increase or decease the weapon damage and delete weapon.
thinking of using a map

	fmt.Println(Trll.Weapon[Bow.Damage])
       // change slice value
	bowd := Trll.Weapon[0]
	fmt.Println(bowd)

Here are two options:

Trll.Weapon[0].Damage = 20
bowd := &Trll.Weapon[0]
bowd.Damage = 10

If Monster.Weapon were []*Weapons instead of []Weapons, then you could write:

bowd := Trll.Weapon[0]
bowd.Damage = 10
2 Likes

great help thank you

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.