How to create a map with key type point (x, y) and value type string in Go

2 Answers

0 votes
package main

import (
    "fmt"
    "strconv"
    "strings"
)

// Point struct with x and y coordinates
type Point struct {
    x int
    y int
}

// Getters
func (p Point) GetX() int {
    return p.x
}

func (p Point) GetY() int {
    return p.y
}

// toString representation
func (p Point) String() string {
    return fmt.Sprintf("(%d, %d)", p.x, p.y)
}

// Key method for map usage
func (p Point) Key() string {
    return fmt.Sprintf("%d,%d", p.x, p.y)
}

func main() {
    // Simulate map[Point]string using string keys
    pointMap := make(map[string]string)

    pointMap[Point{2, 7}.Key()] = "A"
    pointMap[Point{3, 6}.Key()] = "B"
    pointMap[Point{0, 0}.Key()] = "C"

    // Print x and y separately
    for keyStr, value := range pointMap {
        parts := strings.Split(keyStr, ",")
        x, _ := strconv.Atoi(parts[0])
        y, _ := strconv.Atoi(parts[1])
        fmt.Printf("x: %d, y: %d => %s\n", x, y, value)
    }
}



/*
run:

x: 0, y: 0 => C
x: 2, y: 7 => A
x: 3, y: 6 => B

*/

 



answered Aug 10 by avibootz
0 votes
package main

import (
    "fmt"
)

// Point struct with x and y coordinates
type Point struct {
    x int
    y int
}

// Getters
func (p Point) GetX() int {
    return p.x
}

func (p Point) GetY() int {
    return p.y
}

func main() {
    // Use Point struct directly as map key
    pointMap := map[Point]string{}

    // Insert values
    pointMap[Point{x: 2, y: 7}] = "A"
    pointMap[Point{x: 3, y: 6}] = "B"
    pointMap[Point{x: 0, y: 0}] = "C"

    // Print x and y separately
    for point, value := range pointMap {
        fmt.Printf("x: %d, y: %d => %s\n", point.GetX(), point.GetY(), value)
    }
}



/*
run:

x: 0, y: 0 => C
x: 2, y: 7 => A
x: 3, y: 6 => B

*/

 



answered Aug 10 by avibootz
...