Câu hỏi phỏng vấn Golang
Câu hỏi

What would you do if you need a hash displayed in a fixed order?

Câu trả lời

To display a hash in a fixed order in Go, you would need to sort the keys of the hash (map) first, as Go maps do not maintain any inherent order of their keys. Here's how you can achieve this:

  1. Extract the Keys: First, extract the keys from the map into a slice.
  2. Sort the Keys: Use the sort package to sort the slice of keys.
  3. Display the Map: Iterate over the sorted slice of keys and retrieve values from the map for display.

Here is an example implementation in Go:

go Copy
package main

import (
    "fmt"
    "sort"
)

func main() {
    fruits := map[string]int{
        "oranges": 5,
        "apples":  3,
        "bananas": 2,
    }

    // Extract keys to a slice
    keys := make([]string, 0, len(fruits))
    for k := range fruits {
        keys = append(keys, k)
    }

    // Sort keys
    sort.Strings(keys)

    // Display map in sorted order of keys
    for _, k := range keys {
        fmt.Printf("%s: %d\n", k, fruits[k])
    }
}

In this example:

  • A map fruits is created with string keys and integer values.
  • The keys are extracted and sorted.
  • The map is displayed by iterating over the sorted keys, ensuring the output is in a fixed order according to the sorted keys.

This method ensures that the hash is displayed in a predictable order, which can be crucial for tasks like unit testing, where consistent outputs are necessary[19].

Citati...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

How can I check if two slices are equal?

junior

What is dynamic type declaration of a variable in Go?

middle

What is the difference between C.sleep() and time.Sleep() ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào