github.com/neohugo/neohugo@v0.123.8/identity/question.go (about) 1 // Copyright 2024 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package identity 15 16 import "sync" 17 18 // NewQuestion creates a new question with the given identity. 19 func NewQuestion[T any](id Identity) *Question[T] { 20 return &Question[T]{ 21 Identity: id, 22 } 23 } 24 25 // Answer takes a func that knows the answer. 26 // Note that this is a one-time operation, 27 // fn will not be invoked again it the question is already answered. 28 // Use Result to check if the question is answered. 29 func (q *Question[T]) Answer(fn func() T) { 30 q.mu.Lock() 31 defer q.mu.Unlock() 32 33 if q.answered { 34 return 35 } 36 37 q.fasit = fn() 38 q.answered = true 39 } 40 41 // Result returns the fasit of the question (if answered), 42 // and a bool indicating if the question has been answered. 43 func (q *Question[T]) Result() (any, bool) { 44 q.mu.RLock() 45 defer q.mu.RUnlock() 46 47 return q.fasit, q.answered 48 } 49 50 // A Question is defined by its Identity and can be answered once. 51 type Question[T any] struct { 52 Identity 53 fasit T 54 55 mu sync.RWMutex 56 answered bool 57 }