days := []string{"M", "Th", "W", "F", "T", "S", "Su"}
dayToNumber := map[string]int{
        "M":  0,
        "T":  1,
        "W":  2,
        "Th": 3,
        "F":  4,
        "S":  5,
        "Su": 6,
    }
  sort.Slice(days, func(i, j int) bool {
     return dayToNumber[days[i]] < dayToNumber[days[j]]
   })
   fmt.Println(days)

This Go code sorts a slice of days of the week (abbreviated to single or double letters) in the order Monday through Sunday using a map to define the ordering of the days. Here’s how it works:

1. A slice of strings named days is defined and initialized with the abbreviations for the days of the week: “M”, “Th”, “W”, “F”, “T”, “S”, and “Su”.
2. A map named dayToNumber is defined and initialized by mapping each day abbreviation to its corresponding numeric position in the week. This map will be used to define the order in which the days should be sorted.
3. The sort.Slice function is called with days as an argument and a comparison function defined as an anonymous function. This function takes two integer parameters i and j, representing the indices of two elements in the slice to be compared, and returns a boolean indicating whether the element at index i should come before the element at index j in the sorted slice.
4. Inside the comparison function, the dayToNumber map determines the numeric positions of the two compared days. The days are accessed using the indices i and j, and their corresponding numeric positions are retrieved from the map.
5. The function returns true if the numeric position of the day at index i is less than the numeric position of the day at index j. This means the day at index i should come before the day at index j in the sorted slice.
6. After the sort.Slice function has been called, the days slice will be sorted in the order “M”, “T”, “W”, “Th”, “F”, “S”, and “Su”, which corresponds to the order of days in a typical Western calendar.
7. Finally, the fmt.Println function is called with days as an argument to print the sorted slice to the console. The output will be “[M T W Th F S Su]”.

Support On Demand!

                                         
Golang